content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def inSkipTokens(start, end, skip_tokens: list) -> bool: """ Check if start and end index(python) is in one of skip tokens """ for token in skip_tokens: if start >= token[0] and end <= token[1]: return True return False
a51124471eb9f1c3be84f132fc4cce3dad6ef336
43,000
def comp(a,b,av=None,bv=None,domatch=True,out=None) : """ VSCATTER comparison of two different data sets """ if domatch : i1,i2=match.match(a['APOGEE_ID'],b['APOGEE_ID']) gd = np.where(a['NVISITS'][i1] == b['NVISITS'][i2])[0] a=a[i1[gd]] b=b[i2[gd]] fig = vscat(a) vs...
265834ad57d4eae8e2ef4278e56bba593f1af62c
43,001
def create_canvas_obj(stroke_width, drawing_mode, realtime_update, background_image, key, height, width): """ Creating a canvas object in Streamlit with the parameters specified by the user. """ canvas_result = st_canvas( fill_color="rgba(255, 165, 0, 0)", stroke_width=stroke_width, ...
c0bc8b5f82b0fc6f4f2624923de8e8b93e77fa5e
43,002
import time def get_observed_entity_list(): # noqa: E501 """get observed entity list get observed entity list # noqa: E501 :param timestamp: the time that cared :type timestamp: int :rtype: EntitiesResponse """ timestamp = time.time() entities = [] # obtain tcp_link entities ...
2ff032fd62a825d673a513ce7789ae4ed7055713
43,003
def datetime_to_time_str(dattim): """ Converts datetime to a string containing only the time. @rtype : str """ return dattim.strftime(TIME_STR_FORMAT)
a93e124a9ebcf531e5dca1c0816a3a0e6ddf1dfa
43,004
from typing import List from typing import Union def nest_tokens(tokens: List[Token]) -> List[Union[Token, NestedTokens]]: """Convert the token stream to a list of tokens and nested tokens. ``NestedTokens`` contain the open and close tokens and a list of children of all tokens in between (recursively nes...
14e6c803a7ce3c9ce50f47ea69dfd6b7d6e09db6
43,005
import socket import time import select import logging def dnslib_resolve_over_udp(query, dnsservers, timeout, **kwargs): """ http://gfwrev.blogspot.com/2009/11/gfwdns.html http://zh.wikipedia.org/wiki/%E5%9F%9F%E5%90%8D%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%BC%93%E5%AD%98%E6%B1%A1%E6%9F%93 http://support.mic...
2212fad092e573e4e68327f0b9b0cc1f4702a0ee
43,006
def is_restricted(fname): """ Is the filename restricted - not to be downloaded by non question editors? """ if fname in ('datfile.txt', 'datfile.dat', 'qtemplate.html', 'marker.py', 'results.py'): return True if fname.startswith("_"): return True if fname.en...
5da7491791aed0364c685a30854c8d9d268eeb5c
43,007
def getBlock(lines, row): """ Parameters ---------- lines row Returns ------- """ block = [] for i in range(row, len(lines)): if lines[i][0] == 'END': return i, block else: if lines[i][0] != '#': block.append(lines[i])
7c8f8e45084eb9ff92d7c68fc03bf285d98ab2d7
43,008
def serve_suggestions(request): """Returns a list of nodes matching the given query""" # Retrieving the query query = request.GET.get("q") if query: # connecting to mongodb with the credentials defined above client = pymongo.MongoClient(f"mongodb://{USERNAME}:{PASSWORD}@{HOSTNAME}") ...
8e9625da706b0ba0906be8fa0f78e452b0386a88
43,009
from pathlib import Path import tomli def get_project_name() -> str: """Find project name, which is prefix for info distributions. Returns: str: the name of package specified in pyproject.toml Raises: EnvironmentError: if file pyproject.toml is not found. """ pyproject_path = sea...
500c549ba799ef845687c5704abd9f8753366e8c
43,010
import logging def _lsusbv_on_device(bus_id, dev_id): """Calls lsusb -v on device.""" _, raw_output = cmd_helper.GetCmdStatusAndOutputWithTimeout( ['lsusb', '-v', '-s', '%s:%s' % (bus_id, dev_id)], timeout=10) device = {'bus': bus_id, 'device': dev_id} depth_stack = [device] # TODO(jbudorick): Add d...
7063cfc36160bc25ace3912500b772c2c1825ca4
43,011
import math def gcj02_to_wgs84(lng, lat): """ GCJ02(火星坐标系)转GPS84 :param lng:火星坐标系的经度 :param lat:火星坐标系纬度 :return: """ if not in_hz(lng, lat): return lng, lat dlat = transformlat(lng - 105.0, lat - 35.0) dlng = transformlng(lng - 105.0, lat - 35.0) radlat = lat / 180.0 * ...
1fd96b505d9651ed3ad386094d115eb046113d41
43,012
def get_related_sets(node): """Return objectSets that are relationships for a look for `node`. Filters out based on: - id attribute is NOT `pyblish.avalon.container` - shapes and deformer shapes (alembic creates meshShapeDeformed) - set name ends with any from a predefined list - set in not in ...
a901ce6ce367faa01691e6e0131bdcba1e399205
43,013
import pathlib import ast import warnings import shlex import sys def generate_tox_func(env: toxini.Env) -> t.List[str]: """Given a tox env dictionary, returns bash code to run.""" envdir = pathlib.Path(env.settings["envdir"]) if not envdir.exists(): raise RuntimeError( f"Can't generat...
3ad678dc7b475da10d8fc9a32a3672b8cba5c16c
43,014
import re def get_geoinfo(location: str) -> dict: """ Infer geographical ISO information from location :param location: geo location of the person :return: dictionary with ISO geo-information """ mapping = get_country_mapping() if location: search = re.search(r'\((.*?)\)', location...
74f55d45286ac3170282d63383af7a8e473c2381
43,015
def Hl_operator(omega): """ implements Hl operator in eq 20 """ omega_norm = np.linalg.norm(omega) term1 = (1/2)*np.eye(3) if (omega_norm < 1.0e-5): return term1 term2 = np.nan_to_num((omega_norm - np.sin(omega_norm)) / (omega_norm**3)) * skew(omega) term3 = np.nan_to_num(...
839ff879c45a2551e02ad4c95e59207bddf8dab1
43,016
def get_world_inverse_matrix(mobj): """ Returns world inverts matrix of the given Maya object :param mobj: MObject, Maya object we want to retrieve world inverse matrix of :return: MMatrix """ inverse_matrix_plug = api.DependencyNode(mobj).find_plug('worldInverseMatrix', want_networked_plug=Fal...
3be1fdc05c04eaf8ebfd5e1f757900ec2fd496b6
43,017
def sum_of_even_valued_fibonacci_numbers() -> int: """Sum of even valued Fibonacci numbers. The values of the Fibonacci sequence should not exceed four millions. Returns: int: returned sum. """ return sum(get_even_fibonacci_sequence())
1405bb172f82638c7da56b74491ded54e660e8ae
43,018
from typing import Dict from typing import Any def get_event_dict(event: Event) -> Dict[str, Any]: """Get event dict.""" final_event_dict = {} event_dict = event.__dict__.copy() final_event_dict["point"] = event.point.__dict__.copy() final_event_dict["is_site"] = event.is_site final_event_dict...
f75cbdba563fd428b7b13367e155b98cd35c6711
43,019
from datetime import datetime def get_customer_lifetime(df_cust, ref_date, start_date): """ Takes in a customer dataframe and returns the customer lifetime based on a reference date. Parameters: ----------- df_cust : dataframe Customer dataframe ref_date : str ...
8cc20bee96ec61b71e24b9e0e17dd4d5f034cc1f
43,020
def helicsFederateIsAsyncOperationCompleted(fed: 'helics_federate') -> "helics_bool": """ check if the current Asynchronous operation has completed Parameters ---------- * `fed` : the federate to operate on Returns ------- 0 if not completed, 1 if completed """ retur...
282e4831e84212be5eec0dd48968d852e04fbe27
43,021
def svn_fs_change_node_prop(*args): """ svn_fs_change_node_prop(svn_fs_root_t root, char path, char name, svn_string_t value, apr_pool_t pool) -> svn_error_t """ return _fs.svn_fs_change_node_prop(*args)
87c8cd35189257e75c65eea23e6abdb969e283ea
43,022
def macaulay_duration(cashflows, discount_rate): """ Computes the Macaulay Duration of a sequence of cash flows """ discounted_flows = discount(cashflows.index, discount_rate)*cashflows weights = discounted_flows/discounted_flows.sum() return np.average(cashflows.index, weights=weights.squeeze()...
eee20c900ad7b2f65a34ab1d10a1bf73e87cef9f
43,023
def precheck(context): """ calls a function named "precheck_<key>" where <key> is context_key with '-' changed to '_' (e.g. "precheck_ami_id") Checking function should return True if OK, or raise RuntimeError w/ message if not Args: context: a populated EFVersionContext object Returns: True if the p...
c4bb435dc40d9504f710d9c4df4ca11163e037c8
43,024
from pathlib import Path async def print_text(req: Request, request: PrintTextRequest) -> ResponsePayload: """Print a text""" config = Config() database = Database() print_id = database.generate_print_id() username = req.state.user_info["username"] printer = Printer() _print_header(config...
9ca8d3e2e2664aac01cc55456a58520a65a265eb
43,025
def catch_index_error(what, otherwise): """ runs callable 'what' and catches IndexErrors, returning 'otherwise' if one occurred :param what: callable :param otherwise: alternate result in case of IndexError :return: result of 'what' or 'otherwise' in case of IndexError """ try: retur...
9138dcea8464f98fcf84edc4d0991cafe9ebd97c
43,026
def alert(alertID=1): """ Serves an individual alert investigation report for the given alert ID. """ pageState = "{ type: 'alert', dataID: '" + alertID + "' }" return render_template( 'technical/index.html', content=g.config['TECHNICAL_CONFIG'], page=pageState, langa...
86ef70d5fbfa45d4a0f84598bb07347f2bc6b6de
43,027
def decode_data_sequence(data): """Read encapsulated data and return a list of strings. Parameters ---------- data : str String of encapsulated data, typically dataset.PixelData Returns ------- list of bytes All fragments in a list of byte strings """ # Convert data...
ed98e459741cbf741a48f40a0a484c248222886f
43,028
def LF_CG_DISTANCE_SHORT(c): """ This LF is designed to make sure that the compound mention and the gene mention aren't right next to each other. """ return -1 if len(list(get_between_tokens(c))) <= 2 else 0
920a0db568e82f6f841f57ea682b3bfd42a1d9da
43,029
def generate_motions(p, u, a, d, plane_center, bbox, radius=500, n=32): """Generate random robot motions that point sensor at plane Generate n motions that keep the sensor at position p and orientation u pointing at the plane given by a[0] + a[1] + a[2] + d = 0 Args: p: 3D position of sensor o...
5962464cdf33dab9fb1a5d2609ade533e04b95a6
43,030
from datetime import datetime def timesince(dt, default="just now"): """ Returns string representing "time since" e.g. 3 days ago, 5 hours ago etc. """ now = datetime.utcnow() diff = now - dt periods = ( (diff.days / 365, "year", "years"), (diff.days / 30, "month", "m...
3b4ecbd30f7769c746e1b7485f8c84ff626d13e5
43,031
import os def hasAWSEnviornmentalVariables(): """Checks the presence of AWS Credentials in OS envoirnmental variables and returns a bool if True or False.""" access_key = os.environ.get('AWS_ACCESS_KEY_ID') secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY') if access_key and secret_key: ret...
daaa2036d9cd50ea11e51217571d40cc37cb0e2f
43,032
def group_zero_one_loss(y_true, y_pred, group_membership, *, normalize=True, sample_weight=None): """A wrapper around the :any:`sklearn.metrics.zero_one_loss` routine. The arguments remain the same, with `group_membership` added. However, the only positional a...
4f7b664185587bb2852c255f6a8ae791fca0be2f
43,033
import re def list_extracted_7z_files(stdout): """ List all files extracted by 7zip based on the stdout analysis. Based on 7zip Client7z.cpp: static const char *kExtractingString = "Extracting "; """ # FIXME: handle Unicode paths with 7zip command line flags get_file_list = re.compil...
ffe72ca8d86b883f674d19bfe3d48b5732f4faf9
43,034
from typing import Union def build_from_dataframe(data: pd.DataFrame, tz: Union[str, list]=None, unit: Union[str, list]=None, name: Union[str, list]=None, type: Union[str, list]=None ) -> list:...
ae43ef4b198e52df1db07fb9a5207ac0d8479835
43,035
def unauthorized(): """Redirect unauthorized users to Login page.""" flash("You must be logged in to view that page.") return redirect(url_for("auth.login"))
a2f4d45c3f2ab215ba350759102022de849804d6
43,036
def shape(parameter): """ Get the shape of a ``Parameter``. Parameters ---------- parameter: Parameter ``Parameter`` object to get the shape of Returns ------- tuple: shape of the ``Parameter`` object """ return parameter.shape
ceb2b9a6199d980386b306ff329b797dc1815a29
43,037
def readFlatWFS(fn,interp=None): """ Load in data from WFS measurement of flat mirror. Assumes that data was processed using processHAS, and loaded into a .fits file. Scale to microns, strip NaNs. If rotate is set to an array of angles, the rotation angle which minimizes the number of NaNs i...
f3f0872cc071f23c7c68c8cb503a209167968e27
43,038
def filter_specials(letter): """Filter based on dict SPECIAL""" return SPECIAL[letter] if letter in SPECIAL else letter
ef152930615c2eb9158de30ebfa2be773b900e90
43,039
from typing import Union from typing import Sequence def mape_score( y_true: Union[Sequence[float], np.ndarray, pd.Series], y_pred: Union[Sequence[float], np.ndarray, pd.Series], ) -> float: """Calculates the Mean Absolute Percentage Error, a common metric used for Time Series Problems Parameters ...
baa87b285e81eb26323547d0e9d5ea7c5eff8dcd
43,040
def movement_windows_construction(tr, periods, group_arr, reftime, halfwidth=3, debug=False): """ Apply movement windows based on eauqtion described in Huajian Yao, 2004 # movement window construction # | 1 # tgi(Tc) - nTc < t < tgi(Tc) + nTc ...
a8e309b1bb1be70c8f2879d1a79c23674dbd9be6
43,041
import inspect import tempfile import scipy def EKOI(x,n=INFO, small=True,dir=tempDir, sz=500., label=""): """ output x variable name, create an image based on x value and output a string which cause emacs to display the image """ r = "" frame = inspect.currentframe() ff = inspect.getouterfram...
df3fae3335f6003ca276ae69661650fdd7f3be35
43,042
def get_fusion_major_courses(fusion_major_soup): """ :param related_major_soup: SoupParser.soup_jar['융합전공'] :return: ["빅데이터융합", ...] """ lecture_dropdown = fusion_major_soup.find_all('div', {'style': 'height:10em;overflow-y:scroll;'})[1] ret = [] for i in lecture_dropdown.find_all(...
ec053466955547140e458e0d17e8935d81e3da1c
43,043
def setup(hass, base_config): """Start Tentalux platform.""" config = base_config.get(DOMAIN) host = config[CONF_HOST] port = config[CONF_PORT] name = 'tentalux' controller = TentaluxController(host, port) controller.connect() devs = {'light': [], 'scene': [], 'camera': []} # One l...
2d1a26560a2b2ef03b8ecbd74e8fd2dcdd8db278
43,044
def voiced_unvoiced(X, window_size=256, window_step=128, copy=True): """ Voiced unvoiced detection from a raw signal Based on code from: https://www.clear.rice.edu/elec532/PROJECTS96/lpc/code.html Other references: http://www.seas.ucla.edu/spapl/code/harmfreq_MOLRT_VAD.m Parameter...
b850dcd6cbfe23e2ed5316fb591ed473275633ce
43,045
def position_split(position_source, position_cible): """Prend les arguments positions_sources et position_cible et sépare la lettre et le chiffre. Les chiffres sont transformé en entier dans l'objectif d'appliquer des opérations mathématiques. La lettre est transformé en index dans l'objectif d'apli...
51216b32614a6d9dd41216b445b9cc3036abf8f3
43,046
from typing import TextIO import sys def read_waze(*, file: TextIO = sys.stdin) -> Waze: """leitura do mapa do Waze""" max_speed = float(file.readline().strip()) waze = Waze(max_speed) try: while True: from_, to, *vals = file.readline().split() waze.new_street(from_, t...
a9e272f53f86c8ee7784e4903be5b94797d0d237
43,047
def shannon_entropy(mag, magerr): """Shannon entropy (Shannon et al. 1949) is used as a metric to quantify the amount of information carried by a signal. The procedure employed here follows that outlined by (D. Mislis et al. 2015). The probability of each point is given by a Cumulative Distribution Fun...
67628d332a2a0c028d39f3e074968ed5fb9c597f
43,048
import json def load_judgement(ljson): """ Load the raw dump of judgement in format of ljson :ljson: Judgement raw dump filename :returns: @todo """ with open(ljson) as fin: df = pd.DataFrame.from_records([json.loads(l) for l in fin]) df = expand_field(df, 'scores', 'topic_id', '...
d94388c326db4fda70c8595b4bc9aa1f58672e6e
43,049
def _item_attributes_match(crypto_config, plaintext_item, encrypted_item): # type: (CryptoConfig, Dict, Dict) -> Bool """Determines whether the unencrypted values in the plaintext items attributes are the same as those in the encrypted item. Essentially this uses brute force to cover when we don't know the ...
3b1520b05c043e0f3aaec40746646e9297dc4136
43,050
import tempfile def gettempdir(): """ Returns: `fsnative` Like :func:`python3:tempfile.gettempdir`, but always returns a `fsnative` path """ # FIXME: I don't want to reimplement all that logic, reading env vars etc. # At least for the default it works. return path2fsn(tempfil...
90e9424f66d2e9aa2474ba619d19efda51a780a8
43,051
import json def get_all_years(): """ All years report """ return json.dumps(query_for_date(4))
97af82b3116ef18dfa90073b8ca096790d3d519a
43,052
def generate_title_label_pred(tweets_dict): """Generate predicted cluster labels for data points based on title similarity""" global tfidf_titles # Get the list of sample_num number of titles from the dict corpus title_list = corpus_list(tweets_dict, 0, sample_num) # Taking stems and synonyms into account for stri...
7c9d419acd001992df8ad764c55c39697c77f875
43,053
def underline_code( source: str, location: SourceLocation, end_location: SourceLocation, padding: int = 1, ) -> str: """Underline code.""" pos, lineno, colno = location end_pos, end_lineno, end_colno = end_location view_begin = pos view_end = end_pos for _ in range(padding + 1)...
de50934cf8cb692366ea87fe45d4774aee6a3715
43,054
def generateTruth(samples): """ generates truth data is sample infected :param samples: samples to generate truth for :return: truth """ truth = [{'SampleID': sample['SampleID'], 'Truth': decision(sample['CurrentProb'])} for sample in samples] return tru...
8ca0cf4ccdafe97769ab4f8f7a1dc90d9b5b4d37
43,055
def aggregate_single_eval( # noqa: C901 result_dict: dict, all_seeds_for_run: list, eval_name: str ) -> dict: """Mean over seeds of single config run.""" new_results_dict = {} data_temp = result_dict[all_seeds_for_run[0]] # Get all main data source keys ("meta", "stats", "time") data_sources = ...
17edc40ff26dfceecbb85f21dc97ffa52abe6973
43,056
def information(file_name): """ adds information extension, if missing :param file_name: name of file :type file_name: str :returns: file with extension added :rtype: str """ return _add_extension(file_name, Extension.INFORMATION)
125fe007c33e00aceee50e159ce41f494d4ffddc
43,057
from typing import Union from typing import Optional def restrict_chat_member(token: str, chat_id: Union[int, str], user_id: int, permissions: ChatPermissions, until_date: Optional[int] = None ...
ce2069c63fea420593b79d3c72298e346f7d8ac6
43,058
def access_message(user_profile, message_id): # type: (UserProfile, int) -> Tuple[Message, UserMessage] """You can access a message by ID in our APIs that either: (1) You received or have previously accessed via starring (aka have a UserMessage row for). (2) Was sent to a public stream in your r...
f120077e133a09ef94be2ae7ae3aeff2fb4778da
43,059
def transfer_continue_pinyin_to_hanzi(param, model='dag'): """ 全拼音按音节切分后转汉字 :param param: :param model: :return: """ try: if param.strip() == '': raise Exception('invalid param') if is_chinese(param): return param else: pinyin = con...
49e2716bda2c65f2159f0b39b07bbd326353f79a
43,060
import os, subprocess def get_mem_usage(): """ Get memory usage for current process """ pid = os.getpid() process = subprocess.Popen("ps -orss= %s" % pid, shell=True, stdout=subprocess.PIPE) out, _err = process.communicate() return int(out)
6b1897099c8038453eb705b76d0e63dc794dcbb7
43,061
def del_clipboard(): """Delete a clipboard entry""" id = int(request.form.get("id")) cb.delete(id) return ""
71511b9e403b280ffa14d1861c1eaf7c97240b1d
43,062
from typing import Optional from typing import Dict from typing import Callable from typing import Any from typing import List def to_list( mapping: Optional[Dict[Key, Val]], key_transform: Callable[[Key], Any] = str_if_bytes, val_transform: Callable[[Val], Any] = to_redis_type, ) -> List: """Flattens...
c04c351858281d1807ea5e388bb4466217f71d29
43,063
def check_down_diagonal(board): """ Checks to see if one of the players got all the spaces in the diagonal going from top-left corner to bottom-right corner. If so, it returns the symbol for that player. If not, it returns None. """ symbol = board[0][0] for row in range(1, SIZE): if board[...
7cf37de563288482fa6608efa7cb2151ea352ed4
43,064
def get_bbf_file(data_file_name): """Return information from file in bbf/bbf/data/... Do NOT call on import time -- that would make flamedisx unusable to non-XENON folks! """ ensure_repo('XENON1T/bbf.git', BBF_PATH) return fd.get_resource(f'{BBF_PATH}/bbf/data/{data_file_name}')
6be27a840bc73b6290f958a13536aa770b6d6af2
43,065
def load( phonopy_yaml=None, # phonopy.yaml-like must be the first argument. supercell_matrix=None, primitive_matrix=None, is_nac=True, calculator=None, unitcell=None, supercell=None, nac_params=None, unitcell_filename=None, supercell_filename=None, born_filename=None, f...
53197ded23e46c38410acab530301036969f6c92
43,066
import os def get_last_modified(dirs): """Get the last modified time. This method recursively goes through `dirs` and returns the most recent modification time time found. Parameters ---------- dirs : list[str] list of directories to search Returns ------- int mo...
4ebc2679e8869097b8041bbe3ad893905fd94dca
43,067
def vote(): """ allows the governance contract to approve or deny a new value if governance approves, the num_votes counter increases by 1 if governance rejects, the reporter's ALGO stake is sent to the governance contract solidity equivalent: slashMiner() Args: 0) will always be equal...
2020c77b0d765164da81c9b54f28121ed640649f
43,068
def load_w2v_instance(file_path): """ Load a word2vec instance given its file path. :param file_path: File path where the instance is located. :return: Word2vec instance. """ return w2v.Word2Vec.load(file_path)
8399e084e10c31954caef9c6a601a35394a357da
43,069
import requests def get_streets_with_postal_codes_by_city(city_name, way_type=None): """ :param city_name: name of city in English :return: """ query_template_path = core_path() / 'osm' / 'templates' / 'get_streets_with_postal_codes_by_city_name.txt' with query_template_path.open(...
3e88baa1337f00667b0d51ac93d8386cef801712
43,070
def get_maj_answer(votes_per_answer): """ :param votes_per_answer: dictionary with {'1': int, '2': int}, where the ints add up to NBR_ANNOTATORS :return: the majority answers, i.e., number of votes at least half that of the number of annotators; raises error if the answers are tied """ if (len(...
87baeafd2ff39c4aa0ea970f501d1c195ffadecd
43,071
def find_subsequence(sequence, query): """ Find a subsequence in a sequence. Parameters ---------- sequence : Sequence The sequence to find the subsequence in. query : Sequence The potential subsequence. Its alphabet must extend the `sequence` alphabet. Retu...
c21e37866df09ac71b7af7a1d33a4a82b168ce17
43,072
def get_retention_period(instance): """ Finds "Backup" tag in list of tags or returns default period (7 days) :param instance: dict Dictionary output with instance details from describe_instances call :return: Retention period for that instance """ for tag in instance["Tags"]: if tag["Ke...
4f122f91ecdae5cead86a8f1703d7c9d19111e16
43,073
def change_password(request, password_change_form=PasswordChangeForm, template_name='woodstock/registration/change_password.html'): """ Displays the change password form """ user = request.user if request.method == 'POST': form = password_change_form(user, request.POST) if form.is_va...
e3fd6546a21e74713670cfe9153d1891c9d97213
43,074
def validate_schema(configuration_dict: dict) -> bool: """ Validate pipeline file schema """ logger.debug("Validating yml schema") # Pipeline pipeline_keys_valid(configuration_dict) version_is_string_type(configuration_dict) # Workflow validate_workflow_definition(configuration_dic...
57bd083bbc4c442032f051460876369ea6a4587c
43,075
def compute_average_passengers_per_stop(instance, passengerData, tram_tour, tram_time_arrival, tram_time_departure): """ INFO function to compute the average number of passengers per stop """ waitPas = compute_waiting_passenger(instance, passengerData, tram_tour, tram_time_arrival, tram_ti...
e114868e59d5b0d13a38182ce5c99eec287662ff
43,076
from .. import kinda def import_data(filepath, use_pickle = False): """ Imports a KinDA object as exported in the format specified by export_data() Imports: - domains, strands, complexes, reactions, resting-sets, resting-set reactions - resting-set stats: => similarity-threshold => c_ma...
183133aec94a980751dfe05de531b0ed06e54b72
43,077
import base64 def invoke_lambda_and_get_duration(lambda_client, payload, function_name): """ Invokes Lambda and return the duration. :param lambda_client: Lambda client. :param payload: payload to send. :param function_name: function name. :return: duration. """ response = lambda_clien...
c8d2b77e4f7bc338efcdfd21db4f7297a625b05c
43,078
def test_816_edge_case(entities, use_ip, save): """ Test that #770 protocol only triggers when the depending deletion is towards the same asn AND not already handled (dependency == noop) """ data = setup_test_data("ixf.member.1") network = entities["net"]["UPDATE_DISABLED_2"] ixlan = en...
996b6c16b1d17a7b5ce519f9e230ff1226b59ed2
43,079
def is_table(doctype): """Returns True if `istable` property (indicating child Table) is set for given DocType.""" def get_tables(): return db.sql_list("select name from tabDocType where istable=1") tables = cache().get_value("is_table", get_tables) return doctype in tables
ad4f7a4bd6d907886a69986ee357d5578309d965
43,080
def _scroll_plot4(images, names, init_z): """ Creates a plot 2x2 image plot of 3d volume images Scrolling changes the displayed slices Parameters ---------- images: list of 4 arrays Each array of shape (z,y,x) or (z,y,x,RGB) names: list of 4 strings Names for each image Us...
86435ada994aa9e02b1f6cf85050f665869da589
43,081
def n_tree(): """ This is the format of this tree t 1 a b c 3 aa ab ba bb ca cb 6 aaa aab aba abb baa bab bba bbb caa cab cba ...
f43a3f90b816b4fc1b172e879e2bb8a56b012747
43,082
import re def reglux_list(mydict,response): """ 遍历正则抓取数据 :param mydict: 字典类型{key:正则表达式,} :param response: request.text需要正则匹配的字符串 :return: 字典类型 """ temp = {} for m,n in mydict.items(): if '' != n: pattern = re.compile(n) matchs = pattern.findall(response)...
f75cad96991fedc6e1ab91a17abc1b8b91be6cdd
43,083
def correct_archetype_areas(prop_architecture_df, architecture_DB, list_uses): """ Corrects the heated area 'Hs_ag' and 'Hs_bg' for buildings with multiple uses. :var prop_architecture_df: DataFrame containing each building's occupancy, construction and renovation data as well as the architectural...
bcb577750bca2de04ec488f213b16a8a5c5a4215
43,084
import random def read_stat(): """ Mocks read_stat as this is a Linux-specific operation. """ return [ { "times": { "user": random.randint(0, 999999999), "nice": random.randint(0, 999999999), "sys": random.randint(0, 999999999), ...
06889ca31c24aa890637ac63283091b096e48443
43,085
import subprocess def _IsMinikubeClusterUp(cluster_name): """Checks if a minikube cluster is running.""" cmd = [_FindMinikube(), 'status', '-p', cluster_name, '-o', 'json'] try: status = run_subprocess.GetOutputJson( cmd, timeout_sec=20, show_stderr=False) return 'Host' in status and status['Hos...
9b217036549ed2e1e1849693769ab51daab56a1e
43,086
def getMaxDouble_DImage(Image): """getMaxDouble_DImage(Image) -> double""" return _ImageFunctions.getMaxDouble_DImage(Image)
4ec93e03ea7d2bc92a71b3a504647166f7848326
43,087
def bfs(graph): """Function that recreates the Breath First Search algorithm, using a queue as its data structure. In this algorithm, when a node is analyzed, it is marked as visited and all of its children are added to the queue (if they are not in it already). The next node to be analyzed is g...
a14671a30d0c61389378ae44641901ec8dce8ac2
43,088
def create_known_points_layer_2d(): """Create points layer with known coordinates Returns ------- layer : napari.layers.Points Points layer. n_points : int Number of points in the points layer known_non_point : list Data coordinates that are known to contain no points. U...
ab944490f81b75c6da808cb468359e67b008fc5c
43,089
def expand_grid_point(point, factor, xoffset, yoffset): """Expand a given georeferenced point by an integer factor, knowing the size of horizontal and vertical area Parameters ---------- point : shapely.geometry.Point Raw point that must be expanded factor : int Number of new po...
c911a839461ece6980872ec77c236970c5ceade3
43,090
from typing import Sequence import secrets import math def weighted_choice(values: Sequence[TValue]) -> TValue: """ A simple weighted choice which favors the items later in the list. Weighting is linear with the first item having a weight of 1, the second having a weight of 2 and so on. values =...
50e741cb7e30fd1814298a16c7aaacec3a4b6943
43,091
import six import inspect def introspect_routine(routine, routine_doc, module_name=None): """Add API documentation information about the function C{routine} to C{routine_doc} (specializing it to C{Routine_doc}).""" routine_doc.specialize_to(RoutineDoc) # Extract the underying function if isinstan...
4f34757c572fa7622db9a3e990c86cbb10265361
43,092
def add_prefix(prefix, name): """Adds prefix to name.""" return "/".join((prefix, name))
f74a40b057059d9cd4527872a17508b301dd6883
43,093
from pathlib import Path def next_job_id(output_dir: Path) -> str: """Return the next job id.""" # The ids are of form "0001", "0002", ... # Such ids are used for naming log files "0001.log" etc. # We look for the first id that haven't been used in the output directory. def make_job_id(n: int) ->...
7fa35775e3bef8cf812b1173880c5be1ad3e6465
43,094
def get_token(request): """The same as validate_token, but return the token object to check the associated user. """ # Coming from HTTP, look for authorization as bearer token token = request.META.get("HTTP_AUTHORIZATION") if token: token = token.split(" ")[-1].strip() try: ...
cefeccf64a07388dde988b01b1f28bb7e6c26f1a
43,095
def isi(spiketrain, axis=-1): """ Return an array containing the inter-spike intervals of the SpikeTrain. Accepts a Neo SpikeTrain, a Quantity array, or a plain NumPy array. If either a SpikeTrain or Quantity array is provided, the return value will be a quantities array, otherwise a plain NumPy ar...
65a89856b2138983bb67d71686701b6d1a5caeb4
43,096
def instance_power_specs_delete(context, instance_uuid, session=None): """ Removes an existing Server specs from the Database """ return IMPL.instance_power_specs_delete(context, instance_uuid)
c03aa362ef23d3196d25f6ec03e2d2f28467eb34
43,097
def POS(POSInt): """Returns 'F' if position indicator is present. The AllSportCG sends a * in a specific position to indicate which team has posession, and this changes that character to an 'F'. Using font Mattbats, F is a football.""" POSText = "" if POSInt == 42: POSText = "F" return(POSText)
2f0dac3bfd0f803f1a60e740c104414bff29bf27
43,098
from typing import Dict from typing import Sequence def kwargs_2_list(**kwargs) -> Dict[str, Sequence]: """ Convert all single values from keyword arguments into lists. For each argument provided, if the type is not a sequence, convert the single value into a list. Strings are not considered as a...
7a816ee19ceb80c6a311ae142c97c9a1f8ae87dd
43,099