content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Dict from typing import Any async def get_by_name(username: str) -> Dict[str, Any]: """ Retrieve one row based by its name. Return object is a dict. Raises if the record was not found. """ username = username.lower() for user in Database: if(user["username"] == us...
eed73179c2e84e9f6b02c09215657d2b221ec601
2,400
import requests def semantics(address: str) -> "show_semantics_page": """ Semantics of address. """ response = requests.get( f"{request.url_root}api/semantics/{EthConfig.DEFAULT_CHAIN}/{address}", headers={"x-api-key": current_app.config["API_KEY"]}, ) return show_semantics_page(respon...
df7feaf64bdd40fe5369c49b464990071b87750f
2,401
def update_trail(clt, trail_name, log_group_arn, role_arn): """ Update Trail to integrate with CloudWatch Logs """ try: result = clt.update_trail( Name = trail_name, CloudWatchLogsLogGroupArn = log_group_arn, CloudWatchLogsRoleArn = role_arn, ) except ClientError as e: print(e.r...
b9274f6d012d74d584e5d22f520ecd76cd9301e2
2,402
from typing import Any from typing import Optional def block(**arguments: Any) -> Optional[Blocks]: """Python application interface for creating an initial block file from command line or python code. This method creates an HDF5 file associated with the desired intial flow specification (for each needed ...
fe3576aea6eff240d9a46dccc12a73f5423fd705
2,403
def _low_discrepancy(dim, n, seed=0.5): """Generate a 1d, 2d, or 3d low discrepancy sequence of coordinates. Parameters ---------- dim : one of {1, 2, 3} The dimensionality of the sequence. n : int How many points to generate. seed : float or array of float, shape (dim,) ...
b8aa5a54e1c3fddbe5f4cbcd2527ed63499b6447
2,404
from typing import Dict import requests def get( url: str ) -> Dict[str, object]: """ Returns the sdk GET response :param url: A string url endpoint. :type: str :return: Dict[str, object] """ try: res = requests.get(url, headers=get_headers()) except Exception as e: ...
2135477211298935a95a62e064653f6713942659
2,405
def register(request): """Create an account for a new user""" if request.method == 'POST': data = request.POST.copy() form = tcdUserCreationForm(data) next = request.POST['next'] if form.is_valid(): new_user = User.objects.create_user(username=data['username'], ...
c01cafc378a18127f861d17643527caf95ab87ee
2,406
def set_index_da_ct(da): """Stacks all coordinates into one multindex and automatically generates a long_name""" coordnames = list(da.coords) da_stacked = da.set_index(ct=coordnames) if len(coordnames) == 1: #only one coordinate just rename ct to the coordinate name da_unstacked = da_s...
396b1c629352c3843617588071295684e1f2bf79
2,407
def LikeView(request, pk): """Function view that manages the likes and dislikes of a post""" post = get_object_or_404(Post, id=request.POST.get('post_id')) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: p...
0031b93e1c58d897e9d56ab786c560c76dc3b962
2,408
def set_edge_color_mapping(table_column, table_column_values=None, colors=None, mapping_type='c', default_color=None, style_name=None, network=None, base_url=DEFAULT_BASE_URL): """Map table column values to colors to set the edge color. Args: table_column (str): Name of Cytos...
447b1e63adf3ec44912cdd1b9795d4839dea7912
2,409
def weld_describe(array, weld_type, aggregations): """ Aggregate during the same evaluation as opposed to separately as in Series.agg Parameters ---------- array : np.ndarray or WeldObject to aggregate on weld_type : WeldType of the array aggregations : list of str supp...
12e8b074b588be955be44fd8f697c2a34af187d9
2,410
def roles_required(*roles): """Decorator which specifies that a user must have all the specified roles. Example:: @app.route('/dashboard') @roles_required('admin', 'editor') def dashboard(): return 'Dashboard' The current user must have both the `admin` role and `editor...
9b3f3103b7ada875ec1e20f90afa953f2073c2c1
2,411
import requests def get_all_forms(url): """Given a `url`, it returns all forms from the HTML content""" soup = bs(requests.get(url).content, "html.parser") return soup.find_all("form")
2ffa9b9165ae14de4e410ca638db0bc9db432642
2,412
def cal_max_len(ids, curdepth, maxdepth): """calculate max sequence length""" assert curdepth <= maxdepth if isinstance(ids[0], list): res = max([cal_max_len(k, curdepth + 1, maxdepth) for k in ids]) else: res = len(ids) return res
0a6c4c96d7518b98d69141711272a97426a623b2
2,413
def urlencode(query, doseq=True, quote_via=quote_plus): """ An alternate implementation of Python's stdlib :func:`urllib.parse.urlencode` function which accepts unicode keys and values within the ``query`` dict/sequence; all Unicode keys and values are first converted to UTF-8 before being used to c...
de023be6a81b5ce27a552ede4e7e4e0da4f9e9b5
2,414
def clip_action(action, action_min, action_max): """ Truncates the entries in action to the range defined between action_min and action_max. """ return np.clip(action, action_min, action_max)
f332b1274ecdd8e104de294568d59e7d0ea056ca
2,415
def isGray(image): """Return True if the image has one channel per pixel.""" return image.ndim < 3
0fdee0d1b6a99ab91354f585cf648583e57d5645
2,416
import logging import torch def mat2img(input_matrix, index_matrix): """ Transforms a batch of features of matrix images in a batch of features of vector images. Args: input_matrix (torch.Tensor): The images with shape (batch, features, matrix.size). index_matrix (torch.Tensor): The index...
d822635157c1aeb6c0b52d37082eec5f2a6833b4
2,417
def _check_molecule_format(val): """If it seems to be zmatrix rather than xyz format we convert before returning""" atoms = [x.strip() for x in val.split(";")] if atoms is None or len(atoms) < 1: # pylint: disable=len-as-condition raise QiskitNatureError("Molecule format error: " + val) # An x...
d546251f02c6ee3bfe44256edff439ba4d3b4c31
2,418
def measure_area_perimeter(mask): """A function that takes either a segmented image or perimeter image as input, and calculates the length of the perimeter of a lesion.""" # Measure area: the sum of all white pixels in the mask image area = np.sum(mask) # Measure perimeter: first find which p...
f443b7208c8c452480f0f207153afc5aa1f11d41
2,419
import os import requests def _click_up_params(user_email: str) -> dict: """ Load a Click Up parameters for this user. Args: user_email (str): Email of user making the request. Returns: (dict): A dict containing the elements: 'success': (Boolean) True if successful, o...
4a4a3aedb7f1331acdbc9f36416ae14594c4fca0
2,420
from typing import Any from unittest.mock import Mock def mock_object(**params: Any) -> "Mock": # type: ignore # noqa """creates an object using params to set attributes >>> option = mock_object(verbose=False, index=range(5)) >>> option.verbose False >>> option.index [0, 1, 2, 3, 4] """ ...
52140b52d29a424b3f16f0e26b03c19f4afbb0b4
2,421
def get_words(message): """Get the normalized list of words from a message string. This function should split a message into words, normalize them, and return the resulting list. For splitting, you should split on spaces. For normalization, you should convert everything to lowercase. Args: ...
dec592d3574da70c27368c4642f5fa47d23b5225
2,422
def get_atomic_forces_card(name, **kwargs): """ Convert XML data to ATOMIC_FORCES card :param name: Card name :param kwargs: Dictionary with converted data from XML file :return: List of strings """ try: external_atomic_forces = kwargs['external_atomic_forces'] except KeyError: ...
5ded8abd9b3ce4ba41b14f7edbe5974063cdf08d
2,423
def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ if root is None: return False if sum - root.val == 0 and root.left is None and root.right is None: return True else: return self.hasPathSum(root.left, sum - root.val) or sel...
ffab5b8205aa9785c86ac365bd6e854319138627
2,424
def _(node: IntJoin, ctx: AnnotateContext) -> BoxType: """All references available on either side of the Join nodes are available.""" lt = box_type(node.over) rt = box_type(node.joinee) t = union(lt, rt) node.typ = t return t
c5d2c94f58c019399ebfcc431994ab339f317b0c
2,425
import json def detect_global_table_updates(record): """This will detect DDB Global Table updates that are not relevant to application data updates. These need to be skipped over as they are pure noise. :param record: :return: """ # This only affects MODIFY events. if record['eventName...
43d9cd6558b0e935a4e195e80932104699564230
2,426
from typing import List import warnings def fix_telecined_fades(clip: vs.VideoNode, tff: bool | int | None = None, thr: float = 2.2) -> vs.VideoNode: """ A filter that gives a mathematically perfect solution to fades made *after* telecining (which made perfect IVTC impossible). Thi...
d28b78bdb65ffc0c1d354fbbde25391d7ce389b1
2,427
import os from typing import Dict from typing import Any from typing import List import copy from datetime import datetime import json from typing import Union def compute_statistics(provider_slug, tile_grid=get_default_tile_grid(), filename=None): """ :param export_task_records: ExporTaskRecords is a list of...
13f6a51492235d0f9b9b6211494c105bbd547300
2,428
from typing import Union from typing import Optional from io import StringIO def compare_rdf(expected: Union[Graph, str], actual: Union[Graph, str], fmt: Optional[str] = "turtle") -> Optional[str]: """ Compare expected to actual, returning a string if there is a difference :param expected: expected RDF. C...
f2e128e1c43c5c207e99c30bb32c14f4c4b71798
2,429
def start_engine(engine_name, tk, context): """ Creates an engine and makes it the current engine. Returns the newly created engine object. Example:: >>> import sgtk >>> tk = sgtk.sgtk_from_path("/studio/project_root") >>> ctx = tk.context_empty() >>> engine = sgtk.platform....
bb755d359f5a950aa182545803de0a1ca4d6aaee
2,430
def parse_vaulttext(b_vaulttext): """Parse the vaulttext. Args: b_vaulttext: A byte str containing the vaulttext (ciphertext, salt, crypted_hmac). Returns: A tuple of byte str of the ciphertext suitable for passing to a Cipher class's decrypt() function, a byte str of the salt, and a byte str...
1b1b6e2aaf1893401d93f750248892ffebae26a6
2,431
import sqlite3 def does_column_exist_in_db(db, table_name, col_name): """Checks if a specific col exists""" col_name = col_name.lower() query = f"pragma table_info('{table_name}');" all_rows = [] try: db.row_factory = sqlite3.Row # For fetching columns by name cursor = db.cursor()...
90abc20c9643e93641e37c0e94fd504cbcf09928
2,432
import hmac def make_secure_val(val): """Takes hashed pw and adds salt; this will be the cookie""" return '%s|%s' % (val, hmac.new(secret, val).hexdigest())
6b29f5f3a447bca73ac02a1d7843bdbb6d982db9
2,433
import random def get_ad_contents(queryset): """ Contents의 queryset을 받아서 preview video가 존재하는 contents를 랜덤으로 1개 리턴 :param queryset: Contents queryset :return: contents object """ contents_list = queryset.filter(preview_video__isnull=False) max_int = contents_list.count() - 1 if max_int ...
233d1e5f736a9cff38731dd292d431f098bee17a
2,434
def Image_CanRead(*args, **kwargs): """ Image_CanRead(String filename) -> bool Returns True if the image handlers can read this file. """ return _core_.Image_CanRead(*args, **kwargs)
f82e31860480611baf6a5f920515466c0d37acab
2,435
def flatten(lst): """Flatten a list.""" return [y for l in lst for y in flatten(l)] if isinstance(lst, (list, np.ndarray)) else [lst]
0aed241d06725dee9a99512ab2ea5c3f6c02008d
2,436
def calc_mean_score(movies): """Helper method to calculate mean of list of Movie namedtuples, round the mean to 1 decimal place""" ratings = [m.score for m in movies] mean = sum(ratings) / max(1, len(ratings)) return round(mean, 1)
6f837ff251e6221227ba4fa7da752312437da90f
2,437
def srun(hosts, cmd, srun_params=None): """Run srun cmd on slurm partition. Args: hosts (str): hosts to allocate cmd (str): cmdline to execute srun_params(dict): additional params for srun Returns: CmdResult: object containing the result (exit status, stdout, etc.) of ...
2e339d90c2de4b1ae81f7e4671c1f726a725a68c
2,438
def COSclustering(key, emb, oracle_num_speakers=None, max_num_speaker=8, MIN_SAMPLES=6): """ input: key (str): speaker uniq name emb (np array): speaker embedding oracle_num_speaker (int or None): oracle number of speakers if known else None max_num_speakers (int): maximum number of clusters to ...
a3b967251683da1e29004a937625d7006a0519ed
2,439
import torch def gauss_distance(sample_set, query_set, unlabeled_set=None): """ (experimental) function to try different approaches to model prototypes as gaussians Args: sample_set: features extracted from the sample set query_set: features extracted from the query set query_set: feat...
b7583988d79d70bda9c3ab6ee0690042645ed714
2,440
def make_mps_left(mps,truncate_mbd=1e100,split_s=False): """ Put an mps into left canonical form Args: mps : list of mps tensors The MPS stored as a list of mps tensors Kwargs: truncate_mbd : int The maximum bond dimension to which the mps shoul...
f2de408b82877050bf24a822c54b4520dad40f2e
2,441
def word_after(line, word): """'a black sheep', 'black' -> 'sheep'""" return line.split(word, 1)[-1].split(' ', 1)[0]
cfa16244d00af8556d7955b7edeb90bac0a213ba
2,442
def domain_in_domain(subdomain, domain): """Returns try if subdomain is a sub-domain of domain. subdomain A *reversed* list of strings returned by :func:`split_domain` domain A *reversed* list of strings as returned by :func:`split_domain` For example:: >>> domain_in_domain([...
cb1b3a3f899f13c13d4168c88ca5b9d4ee345e47
2,443
def polygon_from_boundary(xs, ys, xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0, xtol=0.0): """Polygon within box left of boundary given by (xs, ys) xs, ys: coordinates of boundary (ys ordered increasingly) """ xs = np.asarray(xs) ys = np.asarray(ys) xs[xs > xmax-xtol] = xmax xs[xs < xmin+xt...
4e75cd8b11038432224836b427658226d4c820d7
2,444
def is_degenerate(op, tol=1e-12): """Check if operator has any degenerate eigenvalues, determined relative to mean spacing of all eigenvalues. Parameters ---------- op : operator or 1d-array Operator or assumed eigenvalues to check degeneracy for. tol : float How much closer tha...
2d2672c711c1e4320de151484cdeb7463cf0abd8
2,445
def _get_skip_props(mo, include_operational=False, version_filter=True): """ Internal function to skip mo property if not to be considered for sync. """ skip_props = [] for prop in mo.prop_meta: mo_property_meta = mo.prop_meta[prop] if mo_property_meta is None: continue ...
dd24798c84f47a954eb324092c3cfb46c23a062e
2,446
def generate_split_problem(): """Generates a 'Split' problem configuration. Returns (environment, robot, start configuration, goal configuration).""" walls = [rectangle(0, 400, 0, 10), rectangle(0, 400, 290, 300), rectangle(0, 10, 0, 300), rectangle(390, 400, 0, 300), rectangle(18...
a2a3ab0495dcf5a109ed2eb2e92bb0db424edd53
2,447
def problem_generator(difficulty=3): """ This function generates mathematical expressions as string. It is not very smart and will generate expressions that have answers the lex function cannot accept. """ operators = ["/", "*", "+", "-"] numeric_lim = difficulty * 7 output = "" ...
f1859784a065a22adb83c33d46623fcafa470096
2,448
from typing import Tuple import math def logical_factory_dimensions(params: Parameters ) -> Tuple[int, int, float]: """Determine the width, height, depth of the magic state factory.""" if params.use_t_t_distillation: return 12*2, 8*2, 6 # Four T2 factories l1_dista...
95846f5f58e5c342ca81b3f51a9bacfb31bf777a
2,449
import re import argparse def parse_list_or_range(arg): """ Parses a string that represents either an integer or a range in the notation ``<start>:<step>:<stop>``. Parameters ---------- arg : :obj:`str` Integer or range string. Returns ------- int or :obj:`lis...
0d487bd80fc14b763a16bc8a167983a1f7959e3e
2,450
def data(): """ Data providing function: This function is separated from create_model() so that hyperopt won't reload data for each evaluation run. """ d_file = 'data/zinc_100k.h5' data_train, data_test, props_train, props_test, tokens = utils.load_dataset(d_file, "TRANSFORMER", True) ...
354ace6fdfc9f8f9ec0702ea8a0a03853b8d7f49
2,451
from typing import Optional from typing import Dict from typing import Any from typing import List import sys import itertools def make_commands( script: str, base_args: Optional[Dict[str, Any]] = None, common_hyper_args: Optional[Dict[str, List[Any]]] = None, algorithm_hyper_args: Optional[Dict[str, ...
dfa9a6ce7f8752a6617567b5210c33e5f34146bf
2,452
def mongos_program(logger, job_num, executable=None, process_kwargs=None, mongos_options=None): # pylint: disable=too-many-arguments """Return a Process instance that starts a mongos with arguments constructed from 'kwargs'.""" args = [executable] mongos_options = mongos_options.copy() if "port" not ...
a342db697d39e48ea0261e5ddfd89bdd99b6dced
2,453
def markerBeings(): """标记众生区块 Content-Type: application/json { "token":"", "block_id":"" } 返回 json { "is_success":bool, "data": """ try: info = request.get_json() # 验证token token = info["token"] i...
20b73bec5f6c27e365a90fe466e34445592f2bd3
2,454
def get_charges_with_openff(mol): """Starting from a openff molecule returns atomic charges If the charges are already defined will return them without change I not will calculate am1bcc charges Parameters ------------ mol : openff.toolkit.topology.Molecule Examples --------- ...
fa539ef60fda28a4983d632830f3a8ea813f5486
2,455
def parse_mdout(file): """ Return energies from an AMBER ``mdout` file. Parameters ---------- file : os.PathLike Name of Amber output file Returns ------- energies : dict A dictionary containing VDW, electrostatic, bond, angle, dihedral, V14, E14, and total energy. ...
9310b0220d4b96b65e3484adf49edebda039dfad
2,456
from propy.AAComposition import GetSpectrumDict from typing import Optional from typing import List def aa_spectrum( G: nx.Graph, aggregation_type: Optional[List[str]] = None ) -> nx.Graph: """ Calculate the spectrum descriptors of 3-mers for a given protein. Contains the composition values of 8000 3-mers...
dfd657452fda009c4420566f1456dc4bd32271ac
2,457
import hashlib def get_click_data(api, campaign_id): """Return a list of all clicks for a given campaign.""" rawEvents = api.campaigns.get(campaign_id).as_dict()["timeline"] clicks = list() # Holds list of all users that clicked. for rawEvent in rawEvents: if rawEvent["message"] == "Clicked ...
641836d73b2c5b2180a98ffc61d0382be74d2618
2,458
def multi_label_column_to_binary_columns(data_frame: pd.DataFrame, column: str): """ assuming that the column contains array objects, returns a new dataframe with binary columns (True/False) indicating presence of each distinct array element. :data_frame: the pandas DataFrame ...
ab626530181740fc941e8efbbaf091bc06f0a0d8
2,459
from typing import List from typing import Set from pathlib import Path import sys def subrepositories_changed(all_if_master: bool = False) -> List[str]: # pragma: no cover """ Returns a list of the final name components of subrepositories that contain files that are different between the master branch a...
962464acf03d44017475cb5327106c225de777c8
2,460
import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter from matplotlib.colors import LightSource def show_landscape(adata, Xgrid, Ygrid, Zgrid, basis="umap", ...
35611e7b01f8a11948abe97a355be929c684af50
2,461
def _GetBuilderPlatforms(builders, waterfall): """Get a list of PerfBuilder objects for the given builders or waterfall. Otherwise, just return all platforms. """ if builders: return {b for b in bot_platforms.ALL_PLATFORMS if b.name in builders} elif waterfall == 'perf': return bot_pl...
f6d7e636bcbd941b1dde8949c68be295e0aef227
2,462
def meeting_guide(context): """ Display the ReactJS drive Meeting Guide list. """ settings = get_meeting_guide_settings() json_meeting_guide_settings = json_dumps(settings) return { "meeting_guide_settings": json_meeting_guide_settings, "mapbox_key": settings["map"]["key"], ...
46d8d20fcb2bd4dacd45a510f51eaea292da0da6
2,463
import multiprocessing def generate_input_fn(file_path, shuffle, batch_size, num_epochs): """Generates a data input function. Args: file_path: Path to the data. shuffle: Boolean flag specifying if data should be shuffled. batch_size: Number of records to be read at a time. num...
abf9dd66000eca392344f9663fa8418b9e596098
2,464
import numpy def amp_phase_to_complex(lookup_table): """ This constructs the function to convert from AMP8I_PHS8I format data to complex64 data. Parameters ---------- lookup_table : numpy.ndarray Returns ------- callable """ _validate_lookup(lookup_table) def converter(...
dea38027654a5a2b6ab974943dbdc57b36835a8e
2,465
from operator import concat def combine_aqs_cmaq(model, obs): """Short summary. Parameters ---------- model : type Description of parameter `model`. obs : type Description of parameter `obs`. Returns ------- type Description of returned object. """ g...
bbc6ba6faf0f580d35674a912c245349d00d2a95
2,466
import sys def bbknn_pca_matrix( pca, batch_list, neighbors_within_batch=3, n_pcs=50, trim=None, approx=True, n_trees=10, use_faiss=True, metric="angular", set_op_mix_ratio=1, local_connectivity=1, ): """ Scanpy-independent BBKNN variant that runs on a PCA matrix an...
1b21bd83b53c3a6418596e6c9d055f34adc726c5
2,467
def read_1d_spikes(filename): """Reads one dimensional binary spike file and returns a td_event event. The binary file is encoded as follows: * Each spike event is represented by a 40 bit number. * First 16 bits (bits 39-24) represent the neuronID. * Bit 23 represents the sign of spike ...
034d6de1e38734fcfe131027956d781752163c33
2,468
def _parse_step_log(lines): """Parse the syslog from the ``hadoop jar`` command. Returns a dictionary which potentially contains the following keys: application_id: a string like 'application_1449857544442_0002'. Only set on YARN counters: a map from counter group -> counter -> amount, or None...
251b0e89157a1c3fa152cbf50daa5e0b10e17bcc
2,469
import re def is_regex(regex, invert=False): """Test that value matches the given regex. The regular expression is searched against the value, so a match in the middle of the value will succeed. To specifically match the beginning or the whole regex, use anchor characters. If invert is true, th...
0db71b3dae2b2013650b65ecacfe6aed0cd8366b
2,470
def get_obj(obj): """Opens the url of `app_obj`, builds the object from the page and returns it. """ open_obj(obj) return internal_ui_operations.build_obj(obj)
f6deddc62f7f3f59ab93b553c64b758340b5fa6c
2,471
def process(frame): """Process initial frame and tag recognized objects.""" # 1. Convert initial frame to grayscale grayframe = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # For every model: for model, color, parameters in ( (MODEL_FACE, (255, 255, 0), {'scaleFactor': 1.1, 'minNeighbors': ...
c0c977d522f292d6cbb03c4e64eabc3d11342e0f
2,472
from datetime import datetime def tzoffset(): """UTC to America/New_York offset.""" return datetime.timedelta(hours=5)
05e883eeae63ad1dd7b287dd0b331b13b11b8cd1
2,473
import tempfile import subprocess import os def ssh(instance, command, plain=None, extra=None, command_args=None): """Run ssh command. Parameters: instance(MechInstance): a mech instance command(str): command to execute (ex: 'chmod +x /tmp/file') plain(bool): use user/pass au...
16600ff5c1d527c3b10fb2c3382955e8c76f221b
2,474
def KICmag(koi,band): """ Returns the apparent magnitude of given KOI star in given band. returns KICmags(koi)[band] """ return KICmags(koi)[band]
767ff04c9319acd698daa05f084e8ee9c456a628
2,475
from typing import List def list_to_decimal(nums: List[int]) -> int: """Accept a list of positive integers in the range(0, 10) and return a integer where each int of the given list represents decimal place values from first element to last. E.g [1,7,5] => 175 [0,3,1,2] => 312 ...
7727ce610987fc9da03a5e23ec8674d1deb7c7f0
2,476
def str_to_bool(v): """ :type v: str """ return v.lower() in ("true", "1")
3eb7ae9e1fe040504ea57c65ed1cbd48be9269cf
2,477
def home_event_manager(): """ Route for alumni's home :return: """ if "idUsers" in session and session["UserTypes_idUserTypes"] == 2: return redirect("/events") else: session.clear() return redirect("/login")
7facf96fbd5d8bbcb7fb867cac7a150a31185dde
2,478
import os def define_url_service(settings_dict) -> str: """Define the url service for the client. It prioritizes ENV variable over settings module""" url = os.environ.get(defaults.SERVICE_URL_ENV) if url: return url else: return settings_dict.get("WORKFLOW_SERVICE", defaults.SERVIC...
ec7de5359cd5e78ba5f063f183b55e4acd318025
2,479
import hashlib def md5_encode(text): """ 把數據 md5 化 """ md5 = hashlib.md5() md5.update(text.encode('utf-8')) encodedStr = md5.hexdigest().upper() return encodedStr
b08f656f5ab0858accfbf54e03d95635a3598e13
2,480
from typing import Counter def _ngrams(segment, n): """Extracts n-grams from an input segment. Parameters ---------- segment: list Text segment from which n-grams will be extracted. n: int Order of n-gram. Returns ------- ngram_counts: Counter Contain all the ...
580cad34eb03359988eb2ce6f77dad246166b890
2,481
def build_varint(val): """Build a protobuf varint for the given value""" data = [] while val > 127: data.append((val & 127) | 128) val >>= 7 data.append(val) return bytes(data)
46f7cd98b6858c003cd66d87ba9ec13041fcf9db
2,482
import re def python_safe_name(s): """ Return a name derived from string `s` safe to use as a Python function name. For example: >>> s = "not `\\a /`good` -safe name ??" >>> assert python_safe_name(s) == 'not_good_safe_name' """ no_punctuation = re.compile(r'[\W_]', re.MULTILINE).sub ...
463d7c3bf4f22449a0a1c28897654d3ccb5e94cb
2,483
def hash_bytes(hash_type: SupportedHashes, bytes_param: bytes) -> bytes: """Hash arbitrary bytes using a supported algo of your choice. Args: hash_type: SupportedHashes enum type bytes_param: bytes to be hashed Returns: hashed bytes """ hasher = get_hash_obj(hash_type) ha...
8f9c05fd050e6f89d6bc5213c03f4002cc341cb0
2,484
def analyze(osi, num_inc=1, dt=None, dt_min=None, dt_max=None, jd=None): """ Performs an analysis step. Returns 0 if successful, and <0 if fail Parameters ---------- osi num_inc dt dt_min dt_max jd Returns ------- """ op_type = 'analyze' if dt is None:...
6c748a49c5e54cf88a04002d98995f4fd90d5130
2,485
from typing import Any import importlib def load_class(path: str) -> Any: """ Load a class at the provided location. Path is a string of the form: path.to.module.class and conform to the python import conventions. :param path: string pointing to the class to load :return: the requested class obje...
c6ae2cd20f71a68a6ec05ef5693656d0db7f2703
2,486
def dcg_at_k(r, k, method=0): """Score is discounted cumulative gain (dcg) Relevance is positive real values. Can use binary as the previous methods. Example from http://www.stanford.edu/class/cs276/handouts/EvaluationNew-handout-6-per.pdf # >>> r = [3, 2, 3, 0, 0, 1, 2, 2, 3, 0] # >>> dcg_...
a52b2e3735461ea7749f092aa35cfe8a55f33e3f
2,487
def metric_section(data_model, metric, level) -> str: """Return the metric as Markdown section.""" markdown = markdown_header(metric["name"], level=level, index=True) markdown += markdown_paragraph(metric["description"]) markdown += definition_list("Default target", metric_target(metric)) markdown +...
6c02e707b6de7c2d89e7eb590d3d9252f13ae9b7
2,488
import argparse def make_argument_parser(): """ Creates an ArgumentParser to read the options for this script from sys.argv """ parser = argparse.ArgumentParser() parser.add_argument("nifti", help="Nifti file to be processed.") parser.add_argument("--out", default=None, help="Output pickle...
0340c3406e2418b3dce8e1b532181101b3aabf1a
2,489
import os def get_pkgs(rpmdir): """scan a dir of rpms and generate a pkgs structure. first try parsing the filename. if that fails, try parsing the rpm headers. """ pkgs = {} """ pkgs structure: * pkgs is a dict of package name, rpmblob list pairs: pkgs = {name:[rpmblob,rpmblob...], name:[rpmblo...
b1781254be8dc4ed3f9147c2e96fa4d871322075
2,490
def MAKEFOURCC(ch0: str, ch1: str, ch2: str, ch3: str) -> int: """Implementation of Window's `MAKEFOURCC`. This is simply just returning the bytes of the joined characters. `MAKEFOURCC(*"DX10")` can also be implemented by `Bytes(b"DX10")`. Args: ch0 (str): First char ch1 (str): Second ...
91afd9dcc8f1cd8c5ef167bdb560c8bf2d89b228
2,491
def sort_configs(configs): # pylint: disable=R0912 """Sort configs by global/package/node, then by package name, then by node name Attributes: configs (list): List of config dicts """ result = [] # Find all unique keys and sort alphabetically _keys = [] for config in configs: ...
5c05214af42a81b35986f3fc0d8670fbef2e2845
2,492
from pathlib import Path import re import os def read_user_config(): """Returns keys in lowercase of xlwings.conf in the user's home directory""" config = {} if Path(xlwings.USER_CONFIG_FILE).is_file(): with open(xlwings.USER_CONFIG_FILE, "r") as f: for line in f: value...
2d179171c4b2763837fc3e7e7c79280756fdd9e9
2,493
def MakeTableData( visible_results, starred_items, lower_columns, lower_group_by, users_by_id, cell_factories, id_accessor, related_issues, config, context_for_all_issues=None): """Return a list of list row objects for display by EZT. Args: visible_results: list of artifacts to display on one pagin...
aab10e8437cae0a5592dceacf2dc60774706d560
2,494
def _add_student_submit(behave_sensibly): """Allow addition of new students Handle both "good" and "bad" versions (to keep code DRY) """ try: if behave_sensibly: do_add_student_good( first_name=request.forms.first_name, last_name=request.forms.last_n...
780b0e667a841b51b1b64c8c8156cebda3d586e9
2,495
def _get_table_reference(self, table_id): """Constructs a TableReference. Args: table_id (str): The ID of the table. Returns: google.cloud.bigquery.table.TableReference: A table reference for a table in this dataset. """ return TableReference(self, table_id)
e92dc5fbeac84b902e50d5302539503246c39f30
2,496
import os def request_item_js( request ): """ Returns modified javascript file for development. Hit by a `dev_josiah_request_item.js` url; production hits the apache-served js file. """ js_unicode = u'' current_directory = os.path.dirname(os.path.abspath(__file__)) js_path = u'%s/lib/josiah_re...
0078c218b9089b601d497d325e7aad51f2c14cd9
2,497
def get_present_types(robots): """Get unique set of types present in given list""" return {type_char for robot in robots for type_char in robot.type_chars}
75c33e0bf5f97afe93829c51086100f8e2ba13af
2,498
def _deserialize_row(params, mask): """ This is for stochastic vectors where some elements are forced to zero. Such a vector is defined by a number of parameters equal to the length of the vector minus one and minus the number of elements forced to zero. @param params: an array of statistical pa...
004775ef669ce7698570091c7212912d0f309bee
2,499