content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def ReadExactly(from_stream, num_bytes): """Reads exactly num_bytes from a stream.""" pieces = [] bytes_read = 0 while bytes_read < num_bytes: data = from_stream.read(min(MAX_READ, num_bytes - bytes_read)) bytes_read += len(data) pieces.append(data) return ''.join(pieces)
5fcd6f204734779e81e7c4b9f263ad4534426278
23,700
import json import phantom.rules as phantom from hashlib import sha256 def indicator_collect(container=None, artifact_ids_include=None, indicator_types_include=None, indicator_types_exclude=None, indicator_tags_include=None, indicator_tags_exclude=None, **kwargs): """ Collect all indicators in a container and...
1e7681f66231e856a9f6a264884556c44fa5b42d
23,701
def remove_duplicates(iterable): """Removes duplicates of an iterable without meddling with the order""" seen = set() seen_add = seen.add # for efficiency, local variable avoids check of binds return [x for x in iterable if not (x in seen or seen_add(x))]
d98fdf8a4be281008fa51344610e5d052aa77cae
23,702
def verify_my_token(user: User = Depends(auth_user)): """ Verify a token, and get basic user information """ return {"token": get_token(user), "email": user.email, "is_admin": user.is_admin, "restricted_job": user.restricted_job}
ee628ab199c7b60ee5fd79103735f6bba51e26a0
23,703
def inv_partition_spline_curve(x): """The inverse of partition_spline_curve().""" c = lambda z: tf.cast(z, x.dtype) assert_ops = [tf.Assert(tf.reduce_all(x >= 0.), [x])] with tf.control_dependencies(assert_ops): alpha = tf.where( x < 8, c(0.5) * x + tf.where( x <= 4, ...
815b91cff13aea862fe1681eed33ebf6497a047b
23,704
def _orbit_bbox(partitions): """ Takes a granule's partitions 'partitions' and returns the bounding box containing all of them. Bounding box is ll, ur format [[lon, lat], [lon, lat]]. """ lon_min = partitions[0]['lon_min'] lat_min = partitions[0]['lat_min'] lon_max = partitions[0]['lon_m...
8e040b549cbdf9587f08a285bd6f867ae580d584
23,705
def GetModel(name: str) -> None: """ Returns model from model pool that coresponds to the given name. Raises GraphicsException if certain model cannot be found. param name: Name of a model. """ if not name in _models: raise GraphicsException(f"No such model '{name}'.") return _models[name]
162b7279f7491c614a72bbb9dc6bbdfd591a7c9c
23,706
def db_to_dict(s_str, i = 0, d = {}): """ Converts a dotbracket string to a dictionary of indices and their pairs Args: s_str -- str: secondary_structure in dotbracket notation KWargs: i -- int: start index d -- dict<index1, index2>: the dictionary so far Returns: dictio...
5440bc318b0b5c8a137e0a3f739031603994e89c
23,707
def identify_event_type(event): """Look at event to determine type of device. Async friendly. """ if EVENT_KEY_COMMAND in event: return EVENT_KEY_COMMAND if EVENT_KEY_SENSOR in event: return EVENT_KEY_SENSOR return "unknown"
d6c504e4edd2993a407ce36eea7688010a46c2be
23,708
def pcolormesh_nan(x: np.ndarray, y: np.ndarray, c: np.ndarray, cmap=None, axis=None): """handles NaN in x and y by smearing last valid value in column or row out, which doesn't affect plot because "c" will be masked too """ mask = np.isfinite(x) & np.isfinite(y) top = None bottom = None f...
cfd26ee1b110099220390c6771668ba1b422278a
23,709
def delete_post(post_id): """Delete a post :param post_id: id of the post object :return: redirect or 404 """ if Post.delete_post(post_id): logger.warning('post %d has been deleted', post_id) return redirect(url_for('.posts')) else: return render_template('page_not_found...
0511287930d66143ee152c5f670918b73fb34250
23,710
from typing import Callable import functools from typing import Any def log_arguments(func: Callable) -> Callable: """ decorate a function to log its arguments and result :param func: the function to be decorated :return: the decorator """ @functools.wraps(func) def wrapper_ar...
a50af7d31049c0da929f649affbd51c12aa6d810
23,711
from importlib import import_module from typing import Union from pathlib import Path from typing import Dict import sys def huggingface_from_pretrained_custom( source: Union[Path, str], tok_config: Dict, trf_config: Dict ) -> HFObjects: """Create a Huggingface transformer model from pretrained weights. Will ...
40a3070985fa298939a03010f0229e835f6e23c8
23,712
import sys def recv_categorical_matrix(socket): """ Receives a matrix of type string from the getml engine """ # ------------------------------------------------------------------------- # Receive shape # By default, numeric data sent over the socket is big endian, # also referred to as ...
d6d02ff96b2d6e1eb1303db3161155adc96c3e38
23,713
import time def collect_gsso_dict(gsso): """ Export gsso as a dict: keys are cls, ind, all (ie cls+ind)""" print('Importing gsso as dict') t0 = time.time() gsso_cls_dict, gsso_ind_dict = _create_gsso_dict(gsso) gsso_all_dict = _create_gsso_dict_all(gsso) print("Executed in %s seconds." % str(t...
cdf14ae2ea6e5fe6e445d7b95a93b0df6423901c
23,714
def H_squared(omega): """Square magnitude of the frequency filter function.""" return 1 / ( (1 + (omega * tau_a) ** 2) * (1 + (omega * tau_r) ** 2) ) * H_squared_heaviside(omega)
60cda08d097901f679ce0fade20b062cb409bbae
23,715
def get_neighbor_distances(ntw, v0, l): """Get distances to the nearest vertex neighbors along connecting arcs. Parameters ---------- ntw : spaghetti.Network spaghetti Network object. v0 : int vertex id l : dict key is tuple (start vertex, end vert...
a7ec81a0c258a691786557e0f66e8ae17c5bbb86
23,716
from typing import Any from typing import List def is_generic_list(annotation: Any): """Checks if ANNOTATION is List[...].""" # python<3.7 reports List in __origin__, while python>=3.7 reports list return getattr(annotation, '__origin__', None) in (List, list)
0ed718eed16e07c27fd5643c18a6e63dc9e38f69
23,717
from pathlib import Path def create_folder(base_path: Path, directory: str, rtn_path=False): """ Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory Parameters ----------- base_path : pathlib.PosixPath Glob...
7c3724b009ef03fc6aa4fbc2bf9da2cbfa4c784d
23,718
import sys import subprocess import time def CheckCallAndFilter(args, stdout=None, filter_fn=None, print_stdout=None, call_filter_on_first_line=False, **kwargs): """Runs a command and calls back a filter function if needed. Accepts all subprocess.Popen() parameters p...
80752fe76efbe9970f390244fb561695572b96f7
23,719
import numpy def extract_track_from_cube(nemo_cube, track_cube, time_pad, dataset_id, nn_finder=None): """ Extract surface track from NEMO 2d cube """ # crop track time st = ga.get_cube_datetime(nemo_cube, 0) et = ga.get_cube_datetime(nemo_cube, -1) # NOTE do no...
ebe226ee7fca3507cebd2d936ef2419c2ec7413a
23,720
import re def get_mean_series_temp(log_frame: pd.DataFrame): """Get temperature time series as mean over CPU cores.""" columns_temp = [c for c in log_frame.columns if re.fullmatch(r"Temp:Core\d+,0", c)] values_temp = log_frame[columns_temp].mean(axis=1) return values_temp
2da22c316433460a8b9f9ec53a8e6542bd6da699
23,721
def new_channel(): """Instantiates a dict containing a template for an empty single-point channel. """ return { "channel_name": "myChannel", "after_last": "Goto first point", "alternate_direction": False, "equation": "x", "final_value": 0.0, "optimizer_con...
af05dfda58a0e14f7448f59b057546728dbbeba7
23,722
from typing import Optional def Log1p(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ :param input_vertex: the vertex """ return Vertex(context.jvm_view().Log1pVertex, label, cast_to_vertex(input_vertex))
fddb06841e528ed7014ef75ecab3354d53e4b901
23,723
def test(request): """ Controller for the app home page. """ context = {} return render(request, 'ueb_app/test.html', context)
3d578e9acbcdec1467162f22d71e1c01979ed778
23,724
import os def pre_process_flights(flights_folder): """ Imports and merges flight files inside input folder. """ df_flights = pd.DataFrame() for flight_file in os.listdir(flights_folder): print('Processing flight: '+flight_file) df_flight = pd.read_csv(os.path.join(flights_folder, f...
befad76520a0111a25bc86a1d79ee7a7c74174f2
23,725
def get_node_backups(request, queryset): """ Return dict with backups attribute. """ user_order_by, order_by = get_order_by(request, api_view=VmBackupList, db_default=('-id',), user_default=('-created',)) bkps = get_pager(request, queryset.order_by(*order_b...
5c5c92b1221037805182efeed6da38d413aa5f16
23,726
def xpath(elt, xp, ns, default=None): """Run an xpath on an element and return the first result. If no results were returned then return the default value.""" res = elt.xpath(xp, namespaces=ns) if len(res) == 0: return default else: return res[0]
2252a15d621d01b58c42790622ffa66022e90dac
23,727
from app.controller import Hand def discard(hand): """ Given six cards, return the four to keep """ cut_card = { "value": 16, "suit": "none", "rank": 0, "name": "none", "id": 'uhgfhc' } max_points = -1 card_ids = [] for set_of_four in permutatio...
8d50899bd02a1743128e8d87e74dafc8deea6a76
23,728
def check_response_stimFreeze_delays(data, **_): """ Checks that the time difference between the visual stimulus freezing and the response is positive and less than 100ms. Metric: M = (stimFreeze_times - response_times) Criterion: 0 < M < 0.100 s Units: seconds [s] :param data: dict of trial d...
9abe61acd4ce085eb6e9f7b7deb06f6a6bcb8a46
23,729
import vtool.keypoint as ktool def get_invVR_aff2Ds(kpts, H=None): """ Returns matplotlib keypoint transformations (circle -> ellipse) Example: >>> # Test CV2 ellipse vs mine using MSER >>> import vtool as vt >>> import cv2 >>> import wbia.plottool as pt >>> img_fp...
c32f2d3b833ebc7212dec95f0ead393847297be7
23,730
import sys def is_reload(module_name: str) -> bool: """True if the module given by `module_name` should reload the modules it imports. This is the case if `enable_reload()` was called for the module before. """ mod = sys.modules[module_name] return hasattr(mod, module_name.replace('.', '_') +...
76e169d6e55203c921dc09cc4c9530c1cf104516
23,731
def get_string(string_name): """ Gets a string from the language file """ if string_name in lang_file[lang]: return lang_file[lang][string_name] elif string_name in lang_file["english"]: return lang_file["english"][string_name] else: return string_name
18ed37668394e40bf70110d9dd26f2a739a6e2e3
23,732
import math import logging def build_streambed(x_max, set_diam): """ Build the bed particle list. Handles calls to add_bed_particle, checks for completness of bed and updates the x-extent of stream when the packing exceeds/under packs within 8mm range. Note: the updates to x-e...
1a4093ebf31b2f19c1144c332addaf5dadad5eee
23,733
def rotate_around_point_highperf_Numpy(xy, radians, origin): """ Rotate a point around a given point. I call this the "high performance" version since we're caching some values that are needed >1 time. It's less readable than the previous function but it's faster. """ adjust_xy = x...
068651134692976e01530a986d6257a45939d741
23,734
def eval(cfg, env, agent): """ Do the evaluation of the current agent :param cfg: configuration of the agent :param env: :param agent: :return: """ print("========= Start to Evaluation ===========") print("Environment:{}, Algorithm:{}".format(cfg.env, cfg.algo)) for i_episode in ...
f0f5f2bf4eabba13fabfd782de53f8a5ef0db982
23,735
def phi(input): """Phi function. :param input: Float (scalar or array) value. :returns: phi(input). """ return 0.5 * erfc(-input/np.sqrt(2))
fd9988c4257c82697a46bee71eb1e67aab286353
23,736
def _is_correct_task(task: str, db: dict) -> bool: """ Check if the current data set is compatible with the specified task. Parameters ---------- task Regression or classification db OpenML data set dictionary Returns ------- bool True if the task and the da...
49790d8e2b7a16ee9b3ca9c8bc6054fde28b3b6f
23,737
import re def is_valid_semver(version: str) -> bool: """return True if a value is a valid semantic version """ match = re.match(r'^[0-9]+\.[0-9]+\.[0-9]+(-([0-9a-z]+(\.[0-9a-z]+)*))?$', version) return match is not None
811a29a497515d23169916b9d9450fed6364c966
23,738
from typing import Optional from typing import List async def role_assignments_for_team( name: str, project_name: Optional[str] = None ) -> List[RoleAssignment]: """Gets all role assignments for a team.""" try: return zen_store.get_role_assignments_for_team( team_name=name, project_nam...
3ba5336882978109e4333aead0bf8d5990a52880
23,739
def set_nested_dict_value(input_dict, key, val): """Uses '.' or '->'-splittable string as key and returns modified dict.""" if not isinstance(input_dict, dict): # dangerous, just replace with dict input_dict = {} key = key.replace("->", ".") # make sure no -> left split_key = key.split...
2f2a160348b0c5d5fac955a8c6cec6c0ec0d5f0d
23,740
from unittest.mock import Mock def cube_1(cube_mesh): """ Viewable cube object shifted to 3 on x """ obj = Mock() obj.name = 'cube_1' obj.mode = 'OBJECT' obj.mesh_mock = cube_mesh obj.to_mesh.return_value = cube_mesh obj.matrix_world = Matrix.Identity(4) obj.mesh_mock.vertices = cube_v...
7d60199dcf41a818346e91014b4f041ab14313da
23,741
def deserialize_model_fixture(): """ Returns a deserialized version of an instance of the Model class. This simulates the idea that a model instance would be serialized and loaded from disk. """ class Model: def predict(self, values): return [1] return Model()
946e0cc67e4cb14da9b08e6790d336126bb9e43a
23,742
def _get_bfp_op(op, name, bfp_args): """ Create the bfp version of the operation op This function is called when a bfp layer is defined. See BFPConv2d and BFPLinear below """ op_name = _get_op_name(name, **bfp_args) if op_name not in _bfp_ops: _bfp_ops[name] = _gen_bfp_op(op, name, bfp_a...
27cac342cbb30159ce7d0bbda8c42df4cefea118
23,743
from typing import Sequence def compute_dmdt(jd: Sequence, mag: Sequence, dmdt_ints_v: str = "v20200318"): """Compute dmdt matrix for time series (jd, mag) See arXiv:1709.06257 :param jd: :param mag: :param dmdt_ints_v: :return: """ jd_diff = pwd_for(jd) mag_diff = pwd_for(mag) ...
af6f7c59de8ec7b38f22f3ffa5e3d17641b9ed32
23,744
def all_bin_vecs(arr, v): """ create an array which holds all 2^V binary vectors INPUT arr positive integers from 1 to 2^V, (2^V, ) numpy array v number of variables V OUTPUT edgeconfs all possible binary vectors, (2^V, V) numpy array """ to_str_func = np.vectorize(lambda x: np.binary_repr(x).zfill(...
1844545f85a1404a0c2bcb094e28e993e369f6df
23,745
def unpack_domains(df): """Unpack domain codes to values. Parameters ---------- df : DataFrame """ df = df.copy() for field, domain in DOMAINS.items(): if field in df.columns: df[field] = df[field].map(domain) return df
9c6c9607439aa24e944d9a8055e741ae3454d0cb
23,746
from bs4 import BeautifulSoup import codecs import logging import sys def validate_saml_response(html): """Parse html to validate that saml a saml response was returned.""" soup = BeautifulSoup(html, "html.parser") xml = None for elem in soup.find_all("input", attrs={"name": "SAMLResponse"}): ...
9a9a8f753433fef78b95d3898df933a8bab287db
23,747
def generate_region_info(region_params): """Generate the `region_params` list in the tiling parameter dict Args: region_params (dict): A `dict` mapping each region-specific parameter to a list of values per FOV Returns: list: The complete set of `region_params` sort...
aa80e1e4ea9693b362fa18a435d886a09ecff533
23,748
def is_decorator(tree, fname): """Test tree whether it is the decorator ``fname``. ``fname`` may be ``str`` or a predicate, see ``isx``. References of the forms ``f``, ``foo.f`` and ``hq[f]`` are supported. We detect: - ``Name``, ``Attribute`` or ``Captured`` matching the given ``fname`` ...
f4fdd760aefae9c1be3d40cc249b242e0be65db5
23,749
def Nbspld1(t, x, k=3): """Same as :func:`Nbspl`, but returns the first derivative too.""" kmax = k if kmax > len(t)-2: raise Exception("Input error in Nbspl: require that k < len(t)-2") t = np.array(t) x = np.array(x)[:, np.newaxis] N = 1.0*((x > t[:-1]) & (x <= t[1:])) dN = np.zero...
f2535888715ec28c2b089c7f92b692b14c26bea7
23,750
def getStyleSheet(): """Returns a stylesheet object""" stylesheet = StyleSheet1() stylesheet.add(ParagraphStyle(name='Normal', fontName="Helvetica", fontSize=10, leading=12)) stylesheet.add(ParagraphS...
fcdb8cc7792254c4c7fb6a55333ad037c914b647
23,751
def parse_faq_entries(entries): """ Iterate through the condensed FAQ entries to expand all of the keywords and answers """ parsed_entries = {} for entry in entries: for keyword in entry["keywords"]: if keyword not in parsed_entries: parsed_entries[keyword] = ...
5258802d9384502f8a00692080cc9ae6ae7e9591
23,752
from datetime import datetime def dh_to_dt(day_str, dh): """decimal hour to unix timestamp""" # return dt.replace(tzinfo=datetime.timezone.utc).timestamp() t0 = datetime.datetime.strptime(day_str, '%Y%m%d') - datetime.datetime(1970, 1, 1) return datetime.datetime.strptime(day_str, '%Y%m%d') + datetime...
f87ec634f49400c178b6cad84f50426f67342868
23,753
def get_statistic(key, key_type, fromtime, endtime, var_names): """ 根据key和时间戳 来获取对应小时统计的报表数据 Paramters: key: key_type: ip, ipc, page, user, did timestamp: t: 生成统计key 对应的type段, 现在默认为None是因为暂时查询key只有ip,ipc 类型的, @todo 视图函数里面扔进来 Return: if key is None: { key(统计leveldb的索引中除了开头...
15f6e0873e5ada69e4ce319756244f6a6ced0a08
23,754
from typing import Sequence from typing import Union from pathlib import Path def run(cmd: Sequence[Union[str, Path]], check=True) -> int: """Run arbitrary command as subprocess""" returncode = run_subprocess( cmd, capture_stdout=False, capture_stderr=False ).returncode if check and returnco...
985eea94264b72db88ae23ebcfdb2d7413390488
23,755
def getDict(fname): """Returns the dict of values of the UserComment""" s = getEXIF(fname, COMMENT_TAG) try: s = s.value except Exception: pass return getDictFromString(s)
9601103a03a97964b2b29379ce21e6710de6a376
23,756
from hetmatpy.degree_weight import default_dwwc_method import inspect import functools import time def path_count_cache(metric): """ Decorator to apply caching to the DWWC and DWPC functions from hetmatpy.degree_weight. """ def decorator(user_function): signature = inspect.signature(user_...
0872b15d52fef0289a72d87632c95a676291dffb
23,757
from typing import Mapping from typing import Set import tqdm def get_metabolite_mapping() -> Mapping[str, Set[Reference]]: """Make the metabolite mapping.""" metabolites_df = get_metabolite_df() smpdb_id_to_metabolites = defaultdict(set) for pathway_id, metabolite_id, metabolite_name in tqdm(metaboli...
ceca1f2bfc993249d9424abec0c5e67b1d456af4
23,758
def has_merge_conflict(commit: str, target_branch: str, remote: str = 'origin') -> bool: """ Returns true if the given commit hash has a merge conflict with the given target branch. """ try: # Always remove the temporary worktree. It's possible that we got # interrupted and left it around. T...
2136f1b60201bd33c3e854ed4df372e0196ea62f
23,759
import os def create_folder(): """Creates a temp_folder on the users desktop""" new_folder_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop\\temp_folder') try: if not os.path.exists(new_folder_path): os.makedirs(new_folder_path) except OSError: print("E...
6e241891b415649902d522dc336d4f75970284c3
23,760
def load_csr(data): """ Loads a PEM X.509 CSR. """ return x509.load_pem_x509_csr(data, default_backend())
edf07190243d7990d2782df240044572243f770b
23,761
def parseIMACS(hdul): """ Parses information from a given HDU, for data produced at IMACS """ start = hdul[0].header['CRVAL1'] step = hdul[0].header['CDELT1'] total = hdul[0].header['NAXIS1'] corr = (hdul[0].header['CRPIX1'] - 1) * step wave = np.arange(start - corr, start + total*st...
35d45a5842977d71375eaa9d07df6051d45ed075
23,762
def boll_cross_func_jit(data:np.ndarray,) -> np.ndarray: """ 布林线和K线金叉死叉 状态分析 Numba JIT优化 idx: 0 == open 1 == high 2 == low 3 == close """ BBANDS = TA_BBANDS(data[:,3], timeperiod=20, nbdevup=2) return ret_boll_cross
8fc68429f5ea94e462327fa57926742161d49911
23,763
from cuml.linear_model import LogisticRegression def rank_genes_groups( X, labels, # louvain results var_names, groups=None, reference='rest', n_genes=100, **kwds, ): """ Rank genes for characterizing groups. Parameters ---------- X : cupy.ndarray of shape (n_cells,...
bd2230d2be098677f62a46becd766edcc1fea36f
23,764
def init_graph_handler(): """Init GraphHandler.""" graph = get_graph_proto() graph_handler = GraphHandler() graph_handler.put({graph.name: graph}) return graph_handler
66b7f9d0b30c435fc3e6fe1152b24d663c31ac6e
23,765
def add_average_column(df, *, copy: bool = False): """Add a column averaging the power on all channels. Parameters ---------- %(df_psd)s An 'avg' column is added averaging the power on all channels. %(copy)s Returns ------- %(df_psd)s The average power across channels h...
0ff995d660ba71bd42ea7ae886b79631e3bd4509
23,766
import fnmatch def _is_globbed(name, glob): """ Return true if given name matches the glob list. """ if not glob: return True return any((fnmatch.fnmatchcase(name, i) for i in glob))
305116367884c8acc9c6f52a73c2cb116abaadbe
23,767
import struct def read_vec_flt(file_or_fd): """[flt-vec] = read_vec_flt(file_or_fd) Read kaldi float vector, ascii or binary input, Parameters ---------- file_or_fd : obj An ark, gzipped ark, pipe or opened file descriptor. Raises ------ ValueError Unsupported data-ty...
f12218f029e18a91666b99e9994ba29d67d62d5a
23,768
def arg_export(name): """Export an argument set.""" def _wrapper(func): _ARG_EXPORTS[name] = func if 'arg_defs' not in dir(func): func.arg_defs = [] return func return _wrapper
a713b22a7fffda50f8a9581362d8fd5ca807cef3
23,769
from typing import OrderedDict def get_od_base( mode = "H+S & B3LYP+TPSS0"): # od is OrderedDict() """ initial parameters are prepared. mode = "H+S & B3LYP+TPSS0" --> ["B3LYP", "TPSS0"] with speration of H and S "H+S & B3LYP" --> ["B3LYP"] with speration of H and S "H+S & TPSSO" --> ["TPSS0"] with sperat...
6a7aa100d8d244d9a0606a08188153e95a0df44b
23,770
import itertools def generate_all_specs( population_specs, treatment_specs, outcome_specs, model_specs, estimator_specs ): """ Generate all combinations of population, treatment, outcome, causal model and estimator """ causal_graph = CausalGraph(treatment_specs, outcome_specs, model_specs) ...
8180bd19d87b69d346edc4fd4442430e0c951873
23,771
def wsFoc(r,psi,L1,z0,alpha): """Return optimum focal surface height at radius r as given by Chase & Van Speybroeck """ return .0625*(psi+1)*(r**2*L1/z0**2)/tan(alpha)**2
90076856f2fbef0cea3d662d1789d8392e9b19e0
23,772
def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap, draw_function=draw_lines, **kwargs): """ `img` should be the output of a Canny transform. draw_function: Which which accepts image & line to render lanes. Default: draw_lines() Returns an image with hough lines drawn. """ ...
586de545e1ad51c5495047f5d513b17ca2f7e369
23,773
from .models import Topography def instances_to_topographies(topographies, surfaces, tags): """Returns a queryset of topographies, based on given instances Given topographies, surfaces and tags are resolved and all topographies are returned which are either - explicitly given - given indirectly b...
a5d94de84046a7218f92fb3f75320b7f78bde446
23,774
from typing import Optional from typing import Union from typing import Tuple import math def plot_histogram( s: pd.Series, *, number_bins: Optional[int] = None, bin_range: Union[Tuple[int, int], Tuple[int, int]] = None, figsize: Optional[Tuple[int, int]] = (8, 6), bin_width: Optional[int] = N...
3f51a9abbf8dde862e18bb21b82f89c34dd6a536
23,775
def get_tracks(): """ Returns all tracks on the minerva DB """ # connect to the database db = connect_minerva_db() # return all the tracks as a list tracks = list(db.tracks.find()) return tracks
65eedeaf32f448a6c32f8c77476dbea6b55a55b0
23,776
def mult_pair(pair): """Return the product of two, potentially large, numbers.""" return pair[0]*pair[1]
b616a0fb706eec5ca8723aa05c273ece079a2350
23,777
def get_only_filename(file_list): """ Get filename from file's path and return list that has only filename. Input: file_list: List. file's paths list. Attribute: file_name: String. "01.jpg" file_name_without_ext: String. "01" Return: filename_list: Only filename lis...
3b9b202a4320825eba9d32170f527c0de6e1bdc6
23,778
import _ctypes def simple_calculate_hmac(sym_key, message, digest_algo=DIGEST_ALGORITHM.SHA256): """Calculates a HMAC of given message using symmetric key.""" message_param = _get_char_param_nullify_if_zero(message) mac = _ctypes.POINTER(_ctypes.c_char)() mac_length = _ctypes...
242f703d062366828f6980d90901a1b803fc426a
23,779
def convert_from_sliced_object(data): """Fix the memory of multi-dimensional sliced object.""" if isinstance(data, np.ndarray) and isinstance(data.base, np.ndarray): if not data.flags.c_contiguous: _log_warning("Usage of np.ndarray subset (sliced data) is not recommended " ...
88361b30137ce9ca646e49b1865d79b65f2693aa
23,780
import pwd import sys import tempfile import os import filecmp import subprocess def write_file(conf, data): """Write the data to the file specified in the conf. If there is an existing file in the destination, compare the new contents with the existing contents. Return True if there is a difference. ...
1d69d6cd2ee2f802ae0af9db66227895551e9816
23,781
def stat_helper(path): """os.path.exists will return None for PermissionError (or any other exception) , leading us to believe a file is not present when it, in fact, is. This is behavior is awful, so stat_helper preserves any exception other than FileNotFoundError. """ try: return path...
32e0863489ca19b55203d31b141d837189655cc2
23,782
from typing import Tuple from datetime import datetime def create_beacon_and_now_datetime( game_name: str = "st", waiting_time: float = 12.0, platform_name: str = "pc" ) -> Tuple[beacons.BeaconBase, datetime.datetime]: """Return a BeaconBase instance with start time to current time.""" ...
cff66d951e2b488a0c8ecd61f6ce5bdbeddae4f7
23,783
def validate(number, check_country=True): """Checks to see if the number provided is a valid IBAN. The country- specific check can be disabled with the check_country argument.""" number = compact(number) # ensure that checksum is valid mod_97_10.validate(number[4:] + number[:4]) # look up the nu...
55ee5423ff025ab9e4332d099e5c2d7b695163dd
23,784
from numpy import array def read_group(fname): """Reads the symmetry group in from the 'rot_perms' styled group output by enum.x. :arg fname: path to the file to read the group from. """ i=0 groupi = [] with open(fname) as f: for line in f: if i > 5: if...
7971781ae157c94329c638d4afd51a871b39498f
23,785
import os import sys def inject_path(path): """ Imports :func: from a python file at :path: and executes it with *args, **kwargs arguments. Everytime this function is called the module is reloaded so that you can alter your debug code while the application is running. The result of the function is re...
e34f8bd53c20f25b362661e87e68e72a77bfcc12
23,786
def find_last_layer(model): """ Find last layer. Args: model (_type_): Model. Returns: _type_: Last layer. """ for layer in reversed(model.layers): return layer
ff82705e4a74d7ad15b3d0e3e030c340b49052ca
23,787
def seconds_to_time(sec): """ Convert seconds into time H:M:S """ return "%02d:%02d" % divmod(sec, 60)
5fe639a9a6ade59258dfb2b3df8426c7e79d19fa
23,788
def _compute_nfp_real(l, u, counts, sizes): """Computes the expected number of false positives caused by using u to approximate set sizes in the interval [l, u], using the real set size distribution. Args: l: the lower bound on set sizes. u: the upper bound on set sizes. counts:...
40abf796ce116a92cd89c813a6343c917e413707
23,789
from typing import Union from typing import Dict from typing import List from typing import Set def is_equal_subset( subset: Union[Dict, List, Set], superset: Union[Dict, List, Set] ) -> bool: """determine if all shared keys have equal value""" if isinstance(subset, dict): return all( ...
4c2edbc73c350783d795ee0aa6e12180642e205c
23,790
import copy import itertools def concatenate_over(argname): """Decorator to "vectorize" functions and concatenate outputs """ def _prepare_args(arg_map, value): params = copy(arg_map) params[argname] = value return params @decorator def _concatenate_over(func, *args, **kwa...
8bdf286566409bc6f8f97e06f5800e495afbc042
23,791
import os def checkFile(path: str): """ Checks if a file exists, exists program if not readable Only used if a file needs to exist """ if not os.path.exists(path): print('File: "' + path + '", is not readable.') exit(0) return path
9ca57e541ecf9579dc6e24ab05f48ea46ec029e9
23,792
import ctypes def logicalToPhysicalPoint(window, x, y): """Converts the logical coordinates of a point in a window to physical coordinates. This should be used when points are received directly from a window that is not DPI aware. @param window: The window handle. @param x: The logical x coordinate. @type x: int...
81aeadcef460ffe1be64a69e64b562cea5dc94d6
23,793
import numba def _node2vec_walks(Tdata, Tindptr, Tindices, sampling_nodes, walklen, return_weight, neighbor_weight): """ Create biased random walks from the transition matrix of a graph in CSR sparse format. Bias method c...
1a6ec24c62168f905a22809fc411036ab9f83b57
23,794
def schedule_prettify(schedule): """ Принимает на вход расписание в формате: [День недели, Время, Тип занятия, Наименование занятия, Имя преподавателя, Место проведения] Например: ['Чт', '13:00 – 14:30', 'ПЗ', 'Физическая культура', '', 'Кафедра'] """ if not schedule: return 'Сегодня зан...
868469b99bb68ec407f6861e12d063bcd6b56236
23,795
def autodelegate(prefix=''): """ Returns a method that takes one argument and calls the method named prefix+arg, calling `notfound()` if there isn't one. Example: urls = ('/prefs/(.*)', 'prefs') class prefs: GET = autodelegate('GET_') def GET_password(self): pass ...
8ea5f555c3b102fc1830a4c616bd71f2dbf98ce4
23,796
def _compute_new_static_size(image, min_dimension, max_dimension): """Compute new static shape for resize_to_range method.""" image_shape = image.get_shape().as_list() orig_height = image_shape[0] orig_width = image_shape[1] num_channels = image_shape[2] # Scale factor such that maximal dimensi...
1cc3a3465f69a8c799ccc529ba95efba0319fdf0
23,797
def deepupdate(original, update): """ Recursively update a dict. Subdict's won't be overwritten but also updated. """ for key, value in original.items(): if key not in update: update[key] = value elif isinstance(value, dict): deepupdate(value, update[key]) ...
fc06aded11a674a0c5815a6f365ff790506af362
23,798
import itertools def _omega_spectrum_odd_c(n, field): """Spectra of groups \Omega_{2n+1}(q) for odd q. [1, Corollary 6] """ n = (n - 1) // 2 q = field.order p = field.char # (1) t = (q ** n - 1) // 2 a1 = [t, t + 1] # (2) a2 = SemisimpleElements(q, n, min_length=2) #...
02512e8368ce1ef048ce0bfa8380ff7e102cdff7
23,799