content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def logoutUser(request): """[summary] Args: request ([Logout]): [Metodo herado de logout de django para cerrar sesión] Returns: [Redirect template]: [Retorna el template del login] """ logout(request) return redirect('/accounts/login/')
67684fb4dfafd0c5f8671553566dd7f6940b4f6c
17,600
def sin_wave(freq, duration=1, offset=0): """Makes a sine wave with the given parameters. freq: float cycles per second duration: float seconds offset: float radians returns: Wave """ signal = SinSignal(freq, offset=offset) wave = signal.make_wave(duration) return wave
f0f0e58d0a864a114aafa24f68b683ac4ec2f419
17,601
def assign_lpvs(lat): """ Given lattice type return 3 lattice primitive vectors""" lpv = zeros((3,3)) if lat=='FCC': lpv[0,1]=1./sqrt(2) lpv[0,2]=1./sqrt(2) lpv[1,0]=1./sqrt(2) lpv[1,2]=1./sqrt(2) lpv[2,0]=1./sqrt(2) lpv[2,1]=1./sqrt(2) elif lat=='SC': ...
ecf599a661446e19e4155f170c41b5ac8271c8cb
17,602
import torch def flatten_and_batch_shift_indices(indices: torch.LongTensor, sequence_length: int) -> torch.Tensor: """``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into dimension 2 of a target tensor, which has size ``(batch_size, sequence_length, embedding_si...
6b283f3baaa4fde17af194f996b7f2dec409fc0b
17,603
def raveled_affinity_watershed( image_raveled, marker_coords, offsets, mask, output ): """Compute affinity watershed on raveled arrays. Parameters ---------- image_raveled : 2D array of float(32), shape (npixels, ndim) The z, y, and x affinities around each pixel. marker_coo...
bc109b59bec4389a851cfc46a8e02648e1809c60
17,604
def get_spike_times(units: pynwb.misc.Units, index, in_interval): """Use bisect methods to efficiently retrieve spikes from a given unit in a given interval Parameters ---------- units: pynwb.misc.Units index: int in_interval: start and stop times Returns ------- """ st = unit...
c121747deec1fcc9b5e317f6ec5e57349604ebc3
17,605
def _make_hours(store_hours): """Store hours is a dictionary that maps a DOW to different open/close times Since it's easy to represent disjoing hours, we'll do this by default Such as, if a store is open from 11am-2pm and then 5pm-10pm We'll slice the times in to a list of floats representing 30 minut...
4845594e59e5dba2790ac1a3c376ddb8e8290995
17,606
def mul_time(t1, factor): """Get the product of the original Time and the number time: Time factor: number returns: Time """ assert valid_time(t1) secods = time_to_int(t1) * factor return int_to_time(secods)
43d9c3a52670b8755590693fe6886748665d81ee
17,607
def create_pmf_from_samples( t_samples_list, t_trunc=None, bin_width=None, num_bins=None): """ Compute the probability distribution of the waiting time from the sampled data. Parameters ---------- t_samples_list : array-like 1-D Samples of the waiting time. t_trunc: int ...
ce14c169ee719979284b01584b7e0523b19f256a
17,608
def box_corner_to_center(boxes): """从(左上,右下)转换到(中间,宽度,高度)""" x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3] cx = (x1 + x2) / 2 cy = (y1 + y2) / 2 w = x2 - x1 h = y2 - y1 boxes = paddle.stack((cx, cy, w, h), axis=-1) return boxes
c07ef637576e5b9ebd8ba43795535e630ccf8b09
17,609
def irrelevant(condition=None, library=None, weblog_variant=None, reason=None): """ decorator, allow to mark a test function/class as not relevant """ skip = _should_skip(library=library, weblog_variant=weblog_variant, condition=condition) def decorator(function_or_class): if not skip: ...
7d2633247569c4ca5bc20d5249e0b49991ae1047
17,610
def get_all_approved(self) -> list: """Get all appliances currently approved .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - appliance - GET - /appliance/approved :return: Returns approved appliances :rtype: l...
4c8c00cce144cf73b2a7b63d1e82a13f28de383c
17,611
import os def get_project_root() -> str: """Get the path to the project root. Returns: str: the path to the project root. """ return os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
afe45a30910049264fbe55551415c7897310ec63
17,612
def bokeh_hover_tooltip( label=False, text=False, image=False, audio=False, coords=True, index=True, custom=None, ): """ ???+ note "Create a Bokeh hover tooltip from a template." - param label: whether to expect and show a "label" field. - param text: whether to expe...
198e76e29d62c12c891c0fe51e947d16f39d65bb
17,613
import math def constant_xavier_initializer(shape, dtype=tf.float32, uniform=True): """Initializer function.""" if not dtype.is_floating: raise TypeError('Cannot create initializer for non-floating point type.') # Estimating fan_in and fan_out is not possible to do perfectly, but we try. # This ...
f11403932f04327b77f38930a8a7a235633449da
17,614
from typing import Dict from typing import Tuple from typing import Any def upload_script(name: str, permission_type: str, content: str, entry_id: str) -> Dict: """ Uploads a script by either given content or file :param name: Script name to upload :param permission_type: Permissions type ...
d33aa3a4f19cfac08d8ee5cb559c0088c6f577bb
17,615
def create_orthogonal(left, right, bottom, top, znear, zfar): """Create a Mat4 orthographic projection matrix.""" width = right - left height = top - bottom depth = zfar - znear sx = 2.0 / width sy = 2.0 / height sz = 2.0 / -depth tx = -(right + left) / width ty = -(top + bottom) /...
3f10bcabe0d95a9832956a7edcef1719c7db0d15
17,616
def update_image_version(name: str, new_version: str): """returns the passed image name modified with the specified version""" parts = name.rsplit(':', 1) return f'{parts[0]}:{new_version}'
cde798361a6c74d22f979fe013e963c46028a7e6
17,617
def compute_entanglement(theta): """Computes the second Renyi entropy of circuits with and without a tardigrade present. Args: - theta (float): the angle that defines the state psi_ABT Returns: - (float): The entanglement entropy of qubit B with no tardigrade initially present ...
bc6d70f1ef76666fa3b4d753f13dc04a8a368374
17,618
import logging def parse_CDS_info(CDS_info): """ Args: CDS_info (python d): 'aliases' (list<alias_list (multiple)>): alias_list list<'locus_tag', str> AND/OR list<'old_locus_tag', str> AND/OR list<'protein_id', st...
d55e5b2c56b42c89c9abeba63cb7c68213688945
17,619
import re def recover_original_schema_name(sql: str, schema_name: str) -> str: """Postgres truncates identifiers to 63 characters at parse time and, as pglast uses bits of PG to parse queries, image names like noaa/climate:64_chars_of_hash get truncated which can cause ambiguities and issues in provenance...
041c747e8722dc1e81a94b29b76ee0eded88992c
17,620
def on_method_not_allowed(error): """Override the HTML 405 default.""" content = {"msg": "Method not allowed"} return jsonify(content), 405
a174592834952beca21c683890ab94c9583544f9
17,621
def dir_name(dir_path): """ 转换零时文件夹、输入文件夹路径 :param dir_path: 主目录路径 :return:[tmp_dir, input_dir, res_dir] """ tmp_dir = dir_path + "tmp\\" input_dir = dir_path + "input\\" res_dir = dir_path + "result\\" return tmp_dir, input_dir, res_dir
9f775b4ace14b178fd7bc0dfa94e5df13e583557
17,622
def profile_binning( r, z, bins, z_name="pm", z_clip=None, z_quantile=None, return_bin=True, plot=True, ): """Bin the given quantity z in r. Parameters ---------- r: 1d array, binned x values z: 1d array, binned y values bins: 1d array, bins Returns ...
f040fe7c7505e628978faf733a91578cb1a04709
17,623
def sequence_to_synergy_sims(inputs, params): """same as sequence to synergy, but prep some other tensors first """ # set up orig seq tensor inputs[DataKeys.ORIG_SEQ] = inputs[DataKeys.FEATURES] # set up thresholds tensor num_interpretation_tasks = len(params["importance_task_indices"]) ...
6abb659be6d1977e7d8a3c7b47f2f60997faf951
17,624
import os def create_invalid_points_feature_class(access_feature_class, invalid_reach_table, invalid_points_feature_class): """ Create a feature class of centroid points for the invalid reaches. :param access_feature_class: Point feature class of all accesses. :param invalid_reach_table: Table of reac...
3d1a0a73efdb34599c261cf6151c2aa29cb2e004
17,625
def _gen_roi_func_constant(constant_roi): """ Return a RoI function which returns a constant radius. See :py:func:`map_to_grid` for a description of the parameters. """ def roi(zg, yg, xg): """ constant radius of influence function. """ return constant_roi return roi
c7c69cf32fb289d5e9c9497474989aa873a231ba
17,626
def less_important_function(num: int) -> str: """ Example which is documented in the module documentation but not highlighted on the main page. :param num: A thing to pass :return: A return value """ return f'{num}'
d6ba0644fc8f4582fb63ceb722b05e824d63312a
17,627
def weth_asset_data(): # pylint: disable=redefined-outer-name """Get 0x asset data for Wrapped Ether (WETH) token.""" return asset_data_utils.encode_erc20( NETWORK_TO_ADDRESSES[NetworkId.GANACHE].ether_token )
0341c1f5c46e05a316c99154be82399145ae9d1a
17,628
def match_known_module_name(pattern): """ Matching with know module name. Args: pattern (Pattern): To be replaced pattern. Returns: str, matched module name, return None if not matched. """ matched_result = [] for ptn, module_name in BUILT_IN_MODULE_NAME.items(): if...
0d76e22517d4fc435101702591e095a96cc5faf7
17,629
def _get_jones_types(name, numba_ndarray_type, corr_1_dims, corr_2_dims): """ Determine which of the following three cases are valid: 1. The array is not present (None) and therefore no Jones Matrices 2. single (1,) or (2,) dual correlation 3. (2, 2) full correlation Parameters ---------- ...
8a9d6f3441c488e2bf1059dd6fcb506a2285d291
17,630
def editing_passport_serial_handler(update: Update, context: CallbackContext) -> int: """Get and save passport serial.""" new_state = editing_pd(update, context, validator=validators.passport_serial_validator, attribute='p...
81c86bffa07376f17dd2c013f5eab42856fa4cea
17,631
import requests def get_overview(ticker: str) -> pd.DataFrame: """Get alpha vantage company overview Parameters ---------- ticker : str Stock ticker Returns ------- pd.DataFrame Dataframe of fundamentals """ # Request OVERVIEW data from Alpha Vantage API s_req...
ddc87f05c8e67f84f2327cf0f06aded0e31e5e8c
17,632
def effective_sample_size(samples): """ Calculates ESS for a matrix of samples. """ try: n_samples, n_params = samples.shape except (ValueError, IndexError): raise ValueError('Samples must be given as a 2d array.') if n_samples < 2: raise ValueError('At least two samples ...
7a31d4a2c2bee133ab264dc793f16d0d6bd866f2
17,633
def get_credentials(credentials_path): """ Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid it returns None. Returns: Credentials, the obtained credential or None """ store = Storage(credentials_path) credentials = s...
b6a6fcd20f8def88c554d276e8f07aae3dc1f536
17,634
def setup(hass, config): """Set up this component.""" conf_track = config[DOMAIN][CONF_TRACK] _LOGGER.info('version %s is starting, if you have ANY issues with this, please report' ' them here: https://github.com/custom-components/custom_updater', __version__) ha_conf_dir = str(hass.co...
d0a18b4c2c3e2c94f19afb66e2e9d2a3d18fea07
17,635
def coset_enumeration_r(fp_grp, Y, max_cosets=None): """ This is easier of the two implemented methods of coset enumeration. and is often called the HLT method, after Hazelgrove, Leech, Trotter The idea is that we make use of ``scan_and_fill`` makes new definitions whenever the scan is incomplete to...
ada1991a732c29c3d14aa5b2a74e54ce57036fc0
17,636
def get_model(**kwargs): """ Returns the model. """ model = ShuffleNetV2(**kwargs) return model
6b226b56fe603a0b703267bc35e2b92f2c6dda7c
17,637
import torch def absolute_filter_change(baseline_state_dict, target_state_dict): """ Calculate sum(abs(K2 - K1) / sum(K1)) Args: baseline_state_dict (dict): state_dict of ori_net target_state_dict (dict): state_dict of finetune_net Returns: sorted_diff (list): sorted values ...
ad4616a03ef80f5a5430a87fd07d70d6bb10f7b7
17,638
import ctypes import sys def run_as_admin(argv=None, debug=False): """ Helper function to run Python script with admin privileges """ shell32 = ctypes.windll.shell32 if argv is None and shell32.IsUserAnAdmin(): return True if argv is None: argv = sys.argv if hasattr(sys, ...
fe6e029d47ef5c486ee2e1c7850c95f36443acc4
17,639
import torch def load_checkpoints(checkpoint_name): """ Load a pretrained checkpoint. :param checkpoint_name: checkpoint filename :return: model.state_dict, source_vocabulary, target_vocabulary, """ # Get checkpoint from file checkpoint = torch.load(checkpoint_name, map_location=torch.dev...
e81f094c811d497504fd1f93a8ee537e6b122bd6
17,640
def _extract_data(prices, n_markets): """ Extract the open, close, high and low prices from the price matrix. """ os = prices[:, :, :n_markets] cs = prices[:, :, n_markets:2*n_markets] hs = prices[:, :, 2*n_markets:3*n_markets] ls = prices[:, :, 3*n_markets:4*n_markets] return os, cs, hs, ls
154af0c8270fbe664b3dd5d07a724b753ff02040
17,641
def make_screen(): """creates the code for a new screen""" return pygame.display.set_mode((800,600))
ca0e23f5583e652207f0297e7363dacaa5a7f085
17,642
import os def listFiles(sDir,ext="_du.mpxml"): """ return 1 list of files """ lsFile = sorted([_fn for _fn in os.listdir(sDir) if _fn.lower().endswith(ext) or _fn.lower().endswith(ext) ]) return lsFile
873f331db44a96fe9d826dbc926354ce4ded6542
17,643
def flip_vert(r, c, row, col, reversed): """1번 연산""" if reversed: row, col = col, row return row - 1 - r, c, reversed
053f6a354e5f6387a528af4ce07290cba370830c
17,644
def get_orders(self, **kwargs): """ | | **Current All Open Orders (USER_DATA)** | *Get all open orders on a symbol. Careful when accessing this with no symbol.* | *If the symbol is not sent, orders for all symbols will be returned in an array.* :API endpoint: ``GET /dapi/v1/openOrders`` :AP...
0561fdeb4863ea08b1644a7695ca7f4ed0622fd9
17,645
def update_amount(amount_id: int): """This function update a data of amount Args: amount_id (int): id of amount Returns: Response: description of amount """ current_app.logger.debug('In PUT /api/amounts/<int:amount_id>') response = None try: # Load data ...
7f85609ab152f22fbcc4aff3f4fb9856bf98d2c7
17,646
def en_13757(data: bytes) -> int: """ Compute a CRC-16 checksum of data with the en_13757 algorithm. :param bytes data: The data to be computed :return: The checksum :rtype: int :raises TypeError: if the data is not a bytes-like object """ _ensure_bytes(data) return _crc_16_en_13757...
85a7793f475f04cca2d7dcf92eeba523fde9b1c2
17,647
def get_agent_supported_features_list_for_extensions(): """ List of features that the GuestAgent currently supports (like Extension Telemetry Pipeline, etc) needed by Extensions. We need to send this list as environment variables when calling extension commands to inform Extensions of all the features t...
8a453286c433b3ecaed2fc402c5d557b335f3935
17,648
def GCMV(image, mask=None): """ :param image: input image, color (3 channels) or gray (1 channel); :param mask: calc gamma value in the mask area, default is the whole image; :return: gamma, and output """ # Step 1. Check the inputs: image if np.ndim(image) == 3 and image.shape[-1] == 3: ...
47070fdda8dcb2507fefd6a5aa922d21481c0896
17,649
from typing import Union def downloadStaffFile(request: HttpRequest, filename: str) -> Union[HttpResponse, FileResponse]: """Serves the specified 'filename' validating the user is logged in and a staff user""" return _downloadFileFromStorage(storages.StaffStorage(), filename)
0e0137f5b5e4140c2d9ff300ed97b7a3e3c37602
17,650
def get_view_renderer_type(*args): """ get_view_renderer_type(v) -> tcc_renderer_type_t Get the type of renderer currently in use in the given view ( 'ui_get_renderer_type' ) @param v (C++: TWidget *) """ return _ida_kernwin.get_view_renderer_type(*args)
e35269d7b77196ebd8ea325db3d6301ffdb63908
17,651
async def create(req): """ Add a new label to the labels database. """ data = req["data"] async with AsyncSession(req.app["pg"]) as session: label = Label( name=data["name"], color=data["color"], description=data["description"] ) session.add(label) try:...
1d7de257f0a3bc1259168821e1fcd6358d4c31c6
17,652
def process_radial_velocity(procstatus, dscfg, radar_list=None): """ Estimates the radial velocity respect to the radar from the wind velocity Parameters ---------- procstatus : int Processing status: 0 initializing, 1 processing volume, 2 post-processing dscfg : dictionary of d...
2114cf4f5524662f80cac69dab45a00729053192
17,653
def brute_force_diagonalize(answers, wordlist=WORDS, quiet=False): """ Find the most cromulent diagonalization for a set of answers, trying all possible orders. See README.md for a cool example of this with 10 answers. As a somewhat artificial example, let's suppose we have these seven answers from...
25725e34dc328cc605cc5dc147547c84de803873
17,654
def train(): """ MNIST training set creator. It returns a reader creator, each sample in the reader is image pixels in [-1, 1] and label in [0, 9]. :return: Training reader creator :rtype: callable """ return reader_creator( paddle.dataset.common.download(TRAIN_IMAGE_URL, 'mnis...
b7008aa61ce49822838c4b30709537396a93f453
17,655
import base64 import hmac import hashlib def sign_v2(key, msg): """ AWS version 2 signing by sha1 hashing and base64 encode. """ return base64.b64encode(hmac.new(key, msg.encode("utf-8"), hashlib.sha1).digest())
1aa54cc2cd3ce20ad5222a889754efda2f4632c3
17,656
def graph_apply(fun, *args): """Currying wrapper around APP(-,-).""" result = fun for arg in args: arg = as_graph(arg) result = APP(result, arg) return result
709306884b37b41c9a7289ad6a372d2b43ede6a9
17,657
def find_hcf(a, b) : """ Finds the Highest Common Factor among two numbers """ #print('HCF : ', a, b) if b == 0 : return a return find_hcf(b, a%b)
818bbc05ab9262e8fd1e8975daf68ca3e0fa6a8b
17,658
def GAU_pdf(x: np.ndarray, mu: float, var: float) -> np.ndarray: """ Probability function of Guassian distribution :param x: ndarray input parameters :param mu: float mean of the distribution :param var: float variance of the distribution :return: ndarray probability of each sample """ k...
9810da4a05d86ac7895a2947a1890fe111faeae4
17,659
def version_compare(a, b): # real signature unknown; restored from __doc__ """ version_compare(a: str, b: str) -> int Compare the given versions; return a strictly negative value if 'a' is smaller than 'b', 0 if they are equal, and a strictly positive value if 'a' is larger than 'b'. """ ...
97b3fd3bbd542d776b75327c88f9e80d776ba248
17,660
def line_status(): """ 设备线路详情 :return: """ device_id = request.args.get("device_id") lines = Line.objects(device_id=device_id).all() result = Monitor.device_status(device_id, lines) result.pop(0) return Success(result)
47ca3cfef469c346ad85b701339941707e2084ea
17,661
import sys import inspect import warnings def namedPositionals(func, args): """Given a function, and a sequence of positional arguments destined for that function, identifies the name for each positional argument. Variable positional arguments are given an automatic name. :arg func: Function which wi...
1d36efd6ad98d6c21b2d75ea54f42dc84a9e52b0
17,662
def _hist_fig(df, pred, c): """ """ bins = np.linspace(0, 1, 15) unlabeled = pred[c][pd.isnull(df[c])].values fig, (ax1, ax2) = plt.subplots(2,1) # top plot: training data pos_labeled = pred[c][(df[c] == 1)&(df["validation"] == False)].values neg_labeled = pred[c][(df[c] =...
6836c0228f2db705642e5f5fa4da6d318674fd55
17,663
import requests def is_responsive(url, code=200): """Check if something responds to ``url`` syncronously""" try: response = requests.get(url) if response.status_code == code: return True except requests.exceptions.RequestException as _e: pass return False
1ed307d7be468157c880bf7e481f255bac449c34
17,664
def fit_and_report(model, X, y, X_valid, y_valid): """ It fits a model and returns train and validation scores. Parameters: model (sklearn classifier model): The sklearn model X (numpy.ndarray): The X part of the train set y (numpy.ndarray): The y part of the train set ...
f993a5410248e5303995f37b5464cb4a57928bcf
17,665
def move_all_generation_to_high_voltage(data): """Move all generation sources to the high voltage market. Uses the relative shares in the low voltage market, **ignoring transmission losses**. In theory, using the production volumes would be more correct, but these numbers are no longer updated since ecoinvent ...
ed9b1fcf60bb1b5645dbd6946fe2e98e6e73ccf3
17,666
from typing import Union def parser_first_text_or_content_if_could(html: etree._Element, query_path: str) -> Union[str, None]: """ 如果解析出的内容是一个数组,默认取的第一个 """ nodes = html.xpath(query_path) if not nodes: return None if len(nodes) > 0: de...
8410280ca71083986af0aa89a312d5082ff36d8d
17,667
from typing import List import os import logging def get_file_paths_from(dir: Text) -> List[Text]: """ list all file paths inside a directory. :param dir: a directory path that need to list. :return: a string list of file paths. """ if not os.path.exists(dir): logging.info('{} does no...
e9e26d01baf7f20802b63f3ebcbfd0b3aac1191c
17,668
def get_all_quantity(results, q_func=None): """ """ quantities = [] for res_name in results: if q_func is not None: # We change the quantity function results[res_name].q_func = q_func min_quantity = results[res_name].min_quantity quantities.append(min_quan...
56d50cacab2dcd7cb1554798a11bb1937436c73e
17,669
import random def generate_example_type_2a(problem, one_step_inferences): """Generates a type 2a training example. Args: problem: a lib.InferenceProblem instance. one_step_inferences: the list of one step inferences that can be reahced form the premises. Returns: An instance of "Example", or...
fafc05b70c7b2a84a2c1476e51fa783f240f2bd5
17,670
import types import sys def name_has_type_hint(name: str, frame: types.FrameType) -> str: """Identifies if a variable name has a type hint associated with it. This can be useful if a user write something like:: name : something use(name) instead of:: name = something us...
1f572d6547e6e66cb499e511a24f8eb3c5c9371b
17,671
import os import yaml def user_input(address, interface=None, name=None, filename='config.yaml'): """ Gather user input for adding an instrument to the YAML configuration file Parameters ---------- address : dict The interface as dict key (i.e. 'pyvisa') and the address as the value n...
3b518a0dd8bcdb54ece2abbb847e585764158c7e
17,672
def query_title_bar_text(shared_state): """return text for title bar, updated when screen changes.""" coll_name = shared_state["active_collection"].name str_value = f"QUERY SOURCE: {coll_name}" return str_value
2ce051cc8d6a87d3c964fba1abb502125b227717
17,673
def input_handler2(): """Run the wx event loop by processing pending events only. This is like inputhook_wx1, but it keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This s...
d9b3887f82b2a9ef19449d58e40ca18b642a2bf4
17,674
import requests def create_upload_record(env, source_id, headers, cookies): """Creates an upload resource via the G.h Source API.""" post_api_url = f"{get_source_api_url(env)}/sources/{source_id}/uploads" print(f"Creating upload via {post_api_url}") res = requests.post(post_api_url, ...
7d8bcebec30be7ccba5406f1afc6a1b267e8e398
17,675
def get_versions(sys): """Import stuff and get versions if module Parameters ---------- sys : module The sys module object. Returns ------- module_versions : dict The module names and corresponding versions. """ module_versions = {} for name, module in sys.modul...
172103da6d6f476080a1c1a33b34ebb4d028df05
17,676
def day05_part1(file: str) -> int: """ Solves advent of code: day05 part1 """ with open(file) as fid: seats = [Seat(line.strip()) for line in fid] highest_seat_num = max(seat.number for seat in seats) return highest_seat_num
5ba399053d3a7e855ded402cea60f59c9d79d9a4
17,677
def GetInput(): """Get player inputs and lower-case the input""" Input = str(input("{:>20s}".format(""))) print("\n \n \n \n \n") return Input.lower()
9d8626a9c9f0615a0453d0804b6b37244ec373c3
17,678
def ldns_fskipcs_l(*args): """LDNS buffer.""" return _ldns.ldns_fskipcs_l(*args)
44e357adf381e11aaccb78441c543438abe75ba1
17,679
def specific_parser(parser, log=False, run_folder=None, mode=None, tot_epochs=None, restoring_rep_path=None, start_from_epoch=None, pretrained_GAN=None, GAN_epoch=None, data_dir_train=None, data_dir_train2=None, data_dir_test=None, data_dir_test2=None, images_log_freq=None, batch...
cbce4c086da986a3232d40ae2d917b921ff64ff2
17,680
import re def to_identifier(text): """Converts text to a valid Python identifier by replacing all whitespace and punctuation and adding a prefix if starting with a digit""" if text[:1].isdigit(): text = '_' + text return re.sub('_+', '_', str(text).translate(TRANS_TABLE))
8c8ca0c52c13a7d78aa9ec2288ef86ec7e10f84a
17,681
def estimate_next_pos(measurement, OTHER = None): """Estimate the next (x, y) position of the wandering Traxbot based on noisy (x, y) measurements.""" if OTHER is None: # Setup Kalman Filter [u, P, H, R] = setup_kalman_filter() # OTHER = {'x': x, 'P': P, 'u': u, 'matrices':[H, R]} ...
a6b6eba0aa7e71a986bc5bed68cc6fb955c02383
17,682
def AutoBusList(*args): """List of Buses or (File=xxxx) syntax for the AutoAdd solution mode.""" # Getter if len(args) == 0: return get_string(lib.Settings_Get_AutoBusList()) # Setter Value, = args if type(Value) is not bytes: Value = Value.encode(codec) lib.Settings_Set_Au...
aab4ae15dd7b12c46eb5a75bb780ac78609273ae
17,683
from typing import Tuple from typing import Optional def validate_inputs(*, input_data: pd.DataFrame) -> Tuple[pd.DataFrame, Optional[dict]]: """Check model inputs for unprocessable values.""" # convert syntax error field names (beginning with numbers) # input_data.rename(columns=config.model_config.vari...
b03e616dc10c734af282d71a650da822e961e93f
17,684
def create_env(n_envs, eval_env=False, no_log=False): """ Create the environment and wrap it if necessary :param n_envs: (int) :param eval_env: (bool) Whether is it an environment used for evaluation or not :param no_log: (bool) Do not log training when doing hyperparameter optim (issue with...
c0d1355cb1ea4446370a71cb49bfb6855799b4b3
17,685
def ellipse(pts, pc=None, ab=None): """ Distance function for the ellipse centered at pc = [xc, yc], with a, b = [a, b] """ if pc is None: pc = [0, 0] if ab is None: ab = [1., 2.] return dist((pts - pc)/ab) - 1.0
7ff99b98aa09d86223afe97a987176f4dc0e0f3d
17,686
def _transform( parsed_date_data: ParsedDate, parsed_output_format_data: ParsedTargetFormat, output_format: str, output_timezone: str, ) -> str: """ This function transform parsed result into target format Parameters ---------- parsed_date_data generated year, month, day, hou...
cc51f2776165bf05af1d97bcc6eb70bd6f03702f
17,687
import logging import uuid def volunteer_dict_from_request(request: flask.Request, actor: str) -> dict: """Creates and returns a dict of volunteer info from the request. `actor` is the ID/email of the person or entity that is triggering this. """ logging.debug('gapps.volunteer_dict_from_request: %s',...
832a9e01dd4873d3781e82f5fc8d8063c1aefa13
17,688
def stop_next_turn(): """ Dirty way to stop the MCTS in a clean way (without SIGINT or SIGTERM)... the mcts finish current turn save data and stop (if you are using dft it can take some time...) write "stop" in the file MCTS/stop_mcts :return: None """ with open(p.f_stop) as f: stop...
eb76187f25f49ae674fefe7969277122bd18e5c8
17,689
from datetime import datetime def pull_request_average_time_between_responses(self, repo_group_id, repo_id=None, group_by='month', time_unit='hours', begin_date=None, end_date=None): """ Avegage time between responeses with merged_status and the time frame :param repo_group_id: The repository's repo_group_id...
8834586b1e761c8ba6033140f753a3ac99780da7
17,690
def create_money(request): """Create money object.""" if request.method == 'POST': form = MoneyForm(request.POST, request.FILES) if form.is_valid(): money = form.save(commit=False) money.owner = request.user money.save() return redirect(money) ...
483eea12a1c2f49dd63fe2a37a529dafe3a4c6c3
17,691
def stripper(reply: str, prefix=None, suffix=None) -> str: """This is a helper function used to strip off reply prefix and terminator. Standard Python str.strip() doesn't work reliably because it operates on character-by-character basis, while prefix/terminator is usually a group of characters. Arg...
b48281a0dedd5d7f3d476943f12ac49720e67476
17,692
def resnet_50_generator(block_fn, lst_layers, num_classes, pruning_method=None, data_format='channels_first', name=None): """Generator for ResNet v1 models. Args: block_fn: String that define...
5f471b7cc3608c11515d0efb088c3c9bee0e20e6
17,693
def bracketBalanced(expression): """Check if an expression is balanced. An expression is balanced if all the opening brackets(i.e. '(, {, [') have a corresponding closing bracket(i.e. '), }, ]'). Args: expression (str) : The expression to be checked. Returns: bool: True if express...
bb6ebeb681fb9425c923a4fdcc41c6158ece332a
17,694
def Leq(pressure, reference_pressure=REFERENCE_PRESSURE, axis=-1): """ Time-averaged sound pressure level :math:`L_{p,T}` or equivalent-continious sound pressure level :math:`L_{p,eqT}` in dB. :param pressure: Instantaneous sound pressure :math:`p`. :param reference_pressure: Reference value :math:`p_0...
bf7c640a361f3c07aef70310a213f2603a441664
17,695
import re def trimBody(body): """ Quick function for trimming away the fat from emails """ # Cut away "On $date, jane doe wrote: " kind of texts body = re.sub( r"(((?:\r?\n|^)((on .+ wrote:[\r\n]+)|(sent from my .+)|(>+[ \t]*[^\r\n]*\r?\n[^\n]*\n*)+)+)+)", "", body, flags=r...
19fcb7313e66d7e710781cf195a7550d050b4848
17,696
def check_host_arp_table_deleted(host, asic, neighs): """ Verifies the ARP entry is deleted. Args: host: instance of SonicHost to run the arp show. neighbor_ip: IP address of the neighbor to verify. arptable: Optional arptable output, if not provided it will be fetched from host. ...
378ff5983e8cc856748daa3509844d194f18476f
17,697
def fit_ellipses(contours): """ Fit ellipses to contour(s). Parameters ---------- contours : ndarray or list Contour(s) to fit ellipses to. Returns ------- ellipses : ndarray or list An array or list corresponding to dimensions to ellipses fitted. """ if isinst...
9246182a1f96ca1691bcddf34271586be93dcf41
17,698
def get_argument_parser() -> ArgumentParser: """ Get command line arguments. """ parser = ArgumentParser( description="Say Hello") subparsers = parser.add_subparsers(title="subcommands") parser_count_above_below = subparsers.add_parser("say-hello") parser_count_above_below.add_argu...
f799991025283bf4ce2dbcceed845662312cd6d0
17,699