content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def alpha_to_weights(alpha): """归一化. 最终截面绝对值和为2. """ alpha = alpha - np.nanmean(alpha, axis=1, keepdims=True) mask_pos = (alpha > 0) mask_neg = (alpha < 0) alpha_pos = imposter(alpha) alpha_pos[mask_pos] = alpha[mask_pos] alpha_pos = alpha_pos / np.nansum(alpha_pos, 1, keepdims=True) alp...
a2a4436b3457fe644a130d463cf501c6cd623f2c
25,500
def complete_with_fake_data_for_warmup(minimum_n_rows_to_fit, X=None, fv_size=None): """Makes fake data to warmup a partial fit process. If no X is given, will return a random minimum_n_rows_to_fit x fv_size matrix (with values between 0 and 1) If X is given, will repeat the rows in a cycle until the minimu...
e201fc50f06945b57a166e4c006252cc892865ed
25,501
from typing import Dict from pathlib import Path def check_integrity(signify: Dict[str, str], snapshot: Path, url: str) -> bool: """Check the integrity of the snapshot and retry once if failed files. signify -- the signify key and a signify signed file with SHA256 checksums snapshot -- the directory wher...
4e33ba5a2652eaba229815eec93dede4aaf6ef5f
25,502
def exp_slow(b, c): """ Returns the value b^c. Property: b^c = b * b^(c-1) Parameter b: the number to raise to a power Precondition: b is a number Parameter c: the exponent Precondition: c is an int >= 0 """ # get in the habit of checking what you can assert type(b) in [floa...
0d58a98f2b7785c9ac69c8a3f4539cdf71d3f27b
25,503
def pick_theme(manual): """ Return theme name based on manual input, prefs file, or default to "plain". """ if manual: return manual pref_init() parser = cp.ConfigParser() parser.read(PREFS_FILE) try: theme = parser.get("theme", "default") except (cp.NoSectionError, c...
6e815a0f46b5de1f1a0ef16ffa0ba21b79ee048f
25,504
import socket def ip2host(ls_input): """ Parameters : list of a ip addreses ---------- Returns : list of tuples, n=2, consisting of the ip and hostname """ ls_output = [] for ip in ls_input: try: x = socket.gethostbyaddr(ip) ls_output.append((ip, x[0]))...
234b42bf0406ae5fb67d2c1caba9f7f3a1e92a0c
25,505
from typing import Tuple from typing import List from pathlib import Path def process_all_content(file_list: list, text_path: str) -> Tuple[list, list]: """ Analyze the whole content of the project, build and return lists if toc_items and landmarks. INPUTS: file_list: a list of all content files text_path: the...
51514892d173adf8a4fe9c3196781c558bc24c6a
25,506
import aiohttp import json def fuel(bot, mask, target, args): """Show the current fuel for Erfurt %%fuel [<city> <value> <type>]... """ """Load configuration""" config = { 'lat': 50.9827792, 'lng': 11.0394426, 'rad': 10 } config.update(bot.config.get(__name__,...
371ecd5e8a7c99032f2544d8256e89475a8d0cd5
25,507
import os def is_executable_binary(file_path): """ Returns true if the file: * is executable * is a binary (i.e not a script) """ if not os.path.isfile(file_path): return False if not os.access(file_path, os.X_OK): return False return is_binary(file_path)
3b1ca2ab87f1568e275b2fe535fe2af7b47804d9
25,508
def findElemArray2D(x, arr2d): """ :param x: a scalar :param arr2d: a 2-dimensional numpy ndarray or matrix Returns a tuple of arrays (rVec, cVec), where the corresponding elements in each are the rows and cols where arr2d[r,c] == x. Returns [] if x not in arr2d. \n Example: \n arr2d =...
37428b16b6f634483d584ef878eea90646d77028
25,509
import itertools def merge(cluster_sentences): """ Merge multiple lists. """ cluster_sentences = list(itertools.chain(*cluster_sentences)) return cluster_sentences
ec5c9bf7a89bf0d047050d3684876ed481617706
25,510
def reverse_str(s: str) -> str: """Reverse a given string""" # Python strings are immutable s = list(s) s_len = len(s) # Using the extra idx as a temp space in list s.append(None) for idx in range(s_len // 2): s[s_len] = s[idx] s[idx] = s[s_len - idx - 1] s[s_len - id...
8568ed59d004afde11bd97e0dba58189a447f954
25,511
def readme(): """Get text from the README.rst""" with open('README.rst') as f: return f.read()
3cf992e2f983d71445e743599dc8b78411bab288
25,512
def exact_account(source_account_id): """ Get the BU id, OU id by the account id in dynamodb table. """ try: response = dynamodb_table.get_item(Key={'AccountId': source_account_id}) except Exception as e: failure_notify("Unable to query account id {0}, detailed exception {1}".format(...
07ff5ef933d00208a5b1aba573c24c5f5987a558
25,513
import re def filter_output(output, regex): """Filter output by defined regex. Output can be either string, list or tuple. Every string is split into list line by line. After that regex is applied to filter only matching lines, which are returned back. :returns: list of matching records ...
d9760a644bb83aee513391966522946a6514ab72
25,514
def carteiralistar(request): """ Metódo para retornar o template de listar carteiras """ usuario = request.user try: # Pega o objeto carteira se já existir carteira = CarteiraCriptomoeda.objects.get(usuario=usuario) # Pega a chave da API e o saldo chave_api = carteira...
32fa51e5c8e6d5a3765b72755cefe24b0ce906a2
25,515
def scrub(text, stop_chars=DEFAULT_STOP_CHARS, reorder_chars=DEFAULT_REORDER_CHARS): """ Scrub text. Runs the relevant functions in an appropriate order. """ text = reorder_stop_chars(text, stop_chars=stop_chars, reorder_chars=reorder_chars) text = remove_columns(text) text = split_as_one_senten...
c24a072e83b6936c04a2e591d2072b0e49849758
25,516
def simulate_evoked_osc(info, fwd, n_trials, freq, label, loc_in_label=None, picks=None, loc_seed=None, snr=None, mu=None, noise_type="white", return_matrix=True, filtering=None, phase_lock=False): """Simulate evoked oscillatory data based on a...
45a7fe74c4f84c96cdbf0aa09059778180064460
25,517
import requests def token_request(): """ Request a Access Token from Vipps. :return: A Access Token """ headers = config['token_request'] url = base_url + '/accesstoken/get' response = requests.post(url, headers=headers) return response.json()
3363179cf526422c53a0eafc8c353ba3f7f29e9f
25,518
from apex import amp def train(args, train_dataset, model, tokenizer, labels, pad_token_label_id): """ Train the model """ if args.local_rank in [-1, 0]: tb_writer = SummaryWriter() args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) train_sampler = RandomSampler(train_...
9d475baa8865f932dd09265d7269eb58f3f31dc2
25,519
def extract_tunneled_layer(tunnel_packet: scapy.layers.l2.Ether, offset: int, protocol: str): """ Extract tunneled layer from packet capture. Args: tunnel_packet (scapy.layers.l2.Ether): the PDU to extract from offset (int): the byte offset of the tunneled protocol in data field of 'packet'...
69596ba7cc5c9db41a2622aa68be1cad89855eb0
25,520
def draw_bbox(img, detections, cmap, random_color=True, figsize=(10, 10), show_text=True): """ Draw bounding boxes on the img. :param img: BGR img. :param detections: pandas DataFrame containing detections :param random_color: assign random color for each objects :param cmap: object colormap ...
f88bb4267d9d389dce589ee26058f4ad1e0fb096
25,521
def print_total_eval_info(data_span_type2model_str2epoch_res_list, metric_type='micro', span_type='pred_span', model_strs=('DCFEE-O', 'DCFEE-M', 'GreedyDec', 'Doc2EDAG'), target_set='test'): """Print the final pe...
e5b754facbf0d203cb143514e143844170400280
25,522
def build_sentence_representation(s): """ Build representation of a sentence by analyzing predpatt output. Returns a weighted list of lists of terms. """ s = merge_citation_token_lists(s) s = remove_qutation_marks(s) lemmatizer = WordNetLemmatizer() raw_lists = [] rep_lists = [] ...
dd070aef016cc034a79412528aabc951605aa83c
25,523
import importlib def load_qconfig(): """ Attemps to load the Qconfig.py searching the current environment. Returns: module: Qconfig module """ try: modspec = importlib.util.find_spec(_QCONFIG_NAME) if modspec is not None: mod = importlib.util.module_from_spec(m...
00ec51be6d16011aa366904a5a0ab8705734c464
25,524
def create_glucose_previous_day_groups(day_groups: dict) -> dict: """ Create a dictionary of glucose subseries, unique to each day in the parent glucose series. Subseries data of each dictionary item will lag item key (date) by 1 day. Keys will be (unique dates in the parent series) + 1 day. Values ...
6b5373b25ab286291cc351bc115c016c83ea660b
25,525
def mean_abs_scaling(series: pd.Series, minimum_scale=1e-6): """Scales a Series by the mean of its absolute value. Returns the scaled Series and the scale itself. """ scale = max(minimum_scale, series.abs().mean()) return series / scale, scale
00f397993a3c51761ef634371d6e26885602e340
25,526
import os def init_dmriprep_wf( anat_only, debug, force_syn, freesurfer, hires, ignore, layout, longitudinal, low_mem, omp_nthreads, output_dir, output_spaces, run_uuid, skull_strip_fixed_seed, skull_strip_template, subject_list, use_syn, work_di...
e5136a8632af08748fdd30b5288850291c6102e7
25,527
def count_total_parameters(): """ Returns total number of trainable parameters in the current tf graph. https://stackoverflow.com/a/38161314/1645784 """ total_parameters = 0 for variable in tf.trainable_variables(): # shape is an array of tf.Dimension shape = variable.get_shape(...
8ee1b116ac3338158c7a43acc570776940bb7e0f
25,528
def create_gradient_rms_plot(sticher_dict: dict[str, GDEFSticher], cutoff_percent=8, moving_average_n=1, x_offset=0, plotter_style: PlotterStyle = None) -> Figure: """ Creates a matplotlib figure, showing a graph of the root meean square of the gradient of the GDEFSticher objects ...
e628250d2c1d4548e6b52d48a8313ffa1b5131fe
25,529
from typing import List from re import T def reverse(ls: List[T]) -> List[T]: """ Reverses a list. :param ls: The list to be reversed :return: The reversed list """ for i in range(len(ls) // 2): ls[i], ls[len(ls) - 1 - i] = ls[len(ls) - 1 - i], ls[i] return ls
eacee56b5325178ec27a13283d64d0155c7a97ed
25,530
def test_get_annotations_not_5( test_gb_file, test_accession, coordination_args, monkeypatch ): """Test get_annotations when length of protein data is not 5.""" def mock_get_gb_file(*args, **kwargs): gb_file = test_gb_file return gb_file def mock_get_record(*args, **kwargs): re...
a9021af24ecb339ebea89d6ad7beb6e4097c5519
25,531
def increment_with_offset(c: str, increment: int, offset: int) -> str: """ Caesar shift cipher. """ return chr(((ord(c) - offset + increment) % 26) + offset)
50b10b6d3aff3dff157dfc46c368ae251ed060bb
25,532
import logging def uploadfiles(): """ function to upload csv to db :return: renders success.html """ # get the uploaded file uploaded_file = request.files['filename'] if uploaded_file.filename != '': csv_to_db(uploaded_file) return render_template('success.html') loggin...
5baa9dfb8930e70ebd37b502a211ae847194e08f
25,533
def static_html(route): """ Route in charge of routing users to Pages. :param route: :return: """ page = get_page(route) if page is None: abort(404) else: if page.auth_required and authed() is False: return redirect(url_for("auth.login", next=request.full_path...
52c74b63c5856a04b294f8e539b4be26deec0209
25,534
import math def getCenterFrequency(filterBand): """ Intermediate computation used by the mfcc function. Compute the center frequency (fc) of the specified filter band (l) This where the mel-frequency scaling occurs. Filters are specified so that their center frequencies are equally spaced on the m...
e043774093c4417658cdfd052d486ea5e30efb81
25,535
import numpy def phi_analytic(dist, t, t_0, k, phi_1, phi_2): """ the analytic solution to the Gaussian diffusion problem """ phi = (phi_2 - phi_1)*(t_0/(t + t_0)) * \ numpy.exp(-0.25*dist**2/(k*(t + t_0))) + phi_1 return phi
49fac597afa876f81ba5774bf82fedcfb88f6c7f
25,536
import subprocess def get_changed_files(base_commit: str, head_commit: str, subdir: str = '.'): """ Get the files changed by the given range of commits. """ cmd = ['git', 'diff', '--name-only', base_commit, head_commit, '--', subdir] files = subprocess.check_output(cmd) ...
ebc0a117f2f11d585475f4781e67331e3ca9a06a
25,537
def geometric_median(X, eps=1e-5): """ calculate the geometric median as implemented in https://stackoverflow.com/a/30305181 :param X: 2D dataset :param eps: :return: median value from X """ y = np.mean(X, 0) while True: D = cdist(X, [y]) nonzeros = (D != 0)[:, 0] ...
9c8b0d69b4f66dc471bcb838b19ecac934493c54
25,538
def distance(bbox, detection): """docstring for distance""" nDetections = detection.shape[0] d = np.zeros(nDetections) D = detection - np.ones([nDetections,1])*bbox for i in xrange(nDetections): d[i] = np.linalg.norm(D[i],1) return d
21c4beea66df1dde96cd91cff459bf10f1b7a41e
25,539
from typing import TextIO from typing import Tuple def _read_float(line: str, pos: int, line_buffer: TextIO ) -> Tuple[float, str, int]: """Read float value from line. Args: line: line. pos: current position. line_buffer: line buffer for nnet3 file. ...
f0c76b2224a17854902aadbe7a715ca00da64932
25,540
def psd_explore( data_folder, channel_index, plot=True, relative=False, reverse=False, export_to_csv=False): """PSD Explore. This assumes use with VR300 for the AD Feedback experiment. data_folder: path to a BciPy data folder with raw data and triggers c...
acbd883ebb9ecbb29efbc9a6a04f722d93b68c68
25,541
def pk_to_p2wpkh_in_p2sh_addr(pk, testnet=False): """ Compressed public key (hex string) -> p2wpkh nested in p2sh address. 'SegWit address.' """ pk_bytes = bytes.fromhex(pk) assert is_compressed_pk(pk_bytes), \ "Only compressed public keys are compatible with p2sh-p2wpkh addresses. See BIP49...
10e9b2659df98b02b5030c1eec1820c9bbdd1a8b
25,542
def remove_imaginary(pauli_sums): """ Remove the imaginary component of each term in a Pauli sum :param PauliSum pauli_sums: The Pauli sum to process. :return: a purely hermitian Pauli sum. :rtype: PauliSum """ if not isinstance(pauli_sums, PauliSum): raise TypeError("not a pauli su...
2edd93f338d4e2dc1878953ced5edf954f509ccc
25,543
def log_sigmoid_deprecated(z): """ Calculate the log of sigmod, avoiding overflow underflow """ if abs(z) < 30: return np.log(sigmoid(z)) else: if z > 0: return -np.exp(-z) else: return z
576d7de9bf61aa32c3e39fc5ca7f4428b43519bb
25,544
def roty(t): """Rotation about the y-axis.""" c = np.cos(t) s = np.sin(t) return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
9c05a96c8c36fd3cd7eee1860574b9242d7543d6
25,545
def ranks_to_metrics_dict(ranks): """Calculates metrics, returns metrics as a dict.""" mean_rank = np.mean(ranks) mean_reciprocal_rank = np.mean(1. / ranks) hits_at = {} for k in (1, 3, 10): hits_at[k] = np.mean(ranks <= k)*100 return { 'MR': mean_rank, 'MRR': mean_reciprocal_rank, 'hi...
60ee20fdf43240e3f0aa0e414fd49bcc52f83446
25,546
def bias_correction(input_data, output_filename='', mask_filename='', method="ants", command="/home/abeers/Software/ANTS/ANTs.2.1.0.Debian-Ubuntu_X64/N4BiasFieldCorrection", temp_dir='./'): """ A catch-all function for motion correction. Will perform motion correction on an input volume depending on the 'm...
5236cff562dc50390146a5902a8f9924457e5426
25,547
def randperm2d(H, W, number, population=None, mask=None): """randperm 2d function genarates diffrent random interges in range [start, end) Parameters ---------- H : {integer} height W : {integer} width number : {integer} random numbers population : {list or num...
a3507c488740e0190673cb0bd920c0c0f15b77a1
25,548
def get_engine(db_credentials): """ Get SQLalchemy engine using credentials. Input: db: database name user: Username host: Hostname of the database server port: Port number passwd: Password for the database """ url = 'postgresql://{user}:{passwd}@{host}:{port}/{db}'.format( ...
ff66c10c7a79b0f5751979f0f5fc74c16d97eac0
25,549
def numpy_to_vtkIdTypeArray(num_array, deep=0): """ Notes ----- This was pulled from VTK and modified to eliminate numpy 1.14 warnings. VTK uses a BSD license, so it's OK to do that. """ isize = vtk.vtkIdTypeArray().GetDataTypeSize() dtype = num_array.dtype if isize == 4: if...
149da1f117968839801f2720c132451045b21fb6
25,550
def denormalize_ged(g1, g2, nged): """ Converts normalized ged into ged. """ return round(nged * (g1.num_nodes + g2.num_nodes) / 2)
214813120d552ef5ece10349978238117fe26cf3
25,551
from datetime import datetime import time def get_current_time(): """just returns time stamp """ time_stamp = datetime.datetime.fromtimestamp( time()).strftime('%Y-%m-%d %H:%M:%S') return time_stamp
236bd2b141c3686bb4c05a18a6d0f0ef3b15ea6b
25,552
import os def get_bad_fname(p, subj, check_exists=True): """Get filename for post-SSS bad channels.""" bad_dir = op.join(p.work_dir, subj, p.bad_dir) if not op.isdir(bad_dir): os.mkdir(bad_dir) bad_file = op.join(bad_dir, 'bad_ch_' + subj + p.bad_tag) if check_exists: bad_file = No...
fe8ad5e09a5da68d2113e1053cdb294c43562444
25,553
import asyncio async def test_script_mode_2(hass, hass_ws_client, script_mode, script_execution): """Test overlapping runs with max_runs > 1.""" id = 1 def next_id(): nonlocal id id += 1 return id flag = asyncio.Event() @callback def _handle_event(_): flag.se...
76a251dc4f2f7aa17e280ee1bcb76aa8333388cb
25,554
def ease_of_movement(high, low, close, volume, n=20, fillna=False): """Ease of movement (EoM, EMV) It relate an asset's price change to its volume and is particularly useful for assessing the strength of a trend. https://en.wikipedia.org/wiki/Ease_of_movement Args: high(pandas.Series): da...
c25720e866b1d4635d7e8256b9ace94f78b463ed
25,555
def Document(docx=None, word_open_xml=None): """ Return a |Document| object loaded from *docx*, where *docx* can be either a path to a ``.docx`` file (a string) or a file-like object. Optionally, ``word_open_xml`` can be specified as a string of xml. Either ``docx`` or `word_open_xml`` may be specif...
565dd4f7f1d815f2e5ef97226d1175283ba942de
25,556
def css_tag(parser, token): """ Renders a tag to include the stylesheet. It takes an optional second parameter for the media attribute; the default media is "screen, projector". Usage:: {% css "<somefile>.css" ["<projection type(s)>"] %} Examples:: {% css "myfile.css" %} ...
b05deebf31c864408df33a41ba95016a06f48e2e
25,557
def camelcase(path): """Applies mixedcase and capitalizes the first character""" return mixedcase('_{0}'.format(path))
484bfcf8797637f56d5d0bdcad6c370f158773c0
25,558
import copy def ImproveData_v2 (Lidar_DataOld,Lidar_Data,Data_Safe,Speed,orientation,orientationm1): """ The function calculates new positions for obstacles now taking into account the car's relative speed in relation to each point. We need the accelerometer for that. Return: ...
2bd6c0f167e65ad4a461d75a95539b68dc0b1a70
25,559
def label_by_track(mask, label_table): """Label objects in mask with track ID Args: mask (numpy.ndarray): uint8 np array, output from main model. label_table (pandas.DataFrame): track table. Returns: numpy.ndarray: uint8/16 dtype based on track count. """ assert mask.s...
9190714e8cfc3955d1aeffd22d20574d14889538
25,560
import zipfile import xml def load_guidata(filename, report): """Check if we have a GUI document.""" report({'INFO'}, "load guidata..") guidata = None zdoc = zipfile.ZipFile(filename) if zdoc: if "GuiDocument.xml" in zdoc.namelist(): gf = zdoc.open("GuiDocument.xml") ...
3828d895a5abb9c6f783eee52d8c747f2f32c20c
25,561
def question_answers(id2line, convos): """ Divide the dataset into two sets: questions and answers. """ questions, answers = [], [] for convo in convos: for index, line in enumerate(convo[:-1]): questions.append(id2line[convo[index]]) answers.append(id2line[convo[index + 1]])...
f2654fcff2b9d90e78750cc8632eea9771361c4d
25,562
import copy def subgrid_kernel(kernel, subgrid_res, odd=False, num_iter=100): """ creates a higher resolution kernel with subgrid resolution as an interpolation of the original kernel in an iterative approach :param kernel: initial kernel :param subgrid_res: subgrid resolution required :retur...
8c62e9a09052faf2f52dc2141b0432b115c79417
25,563
import spacy.en import logging def get_spacy(): """ Loads the spaCy english processor. Tokenizing, Parsing, and NER are enabled. All other features are disabled. Returns: A spaCy Language object for English """ logging.info('Loading spaCy...') nlp = spacy.en.English(tagger=False,...
6abe2c9cb8cb0027c53c5e013d4127829b339699
25,564
import astroobs as obs import re from datetime import datetime def get_JDs(period='102', night=True, arrays=True, verbose=True): """ Get the Julian days for all ESPRESSO GTO runs in a given period. If `night`=True, return the JD of sunset and sunrise. This function returns the runs' start and end in ...
f21aea967e0d1a481d599bf7ffea2316d401a7ea
25,565
def normalize_breton(breton_string: str) -> str: """Applies Breton mutations.""" return (breton_string.strip().lower() @ DO_PREPROCESSING @ DO_SOFT_MUTATION @ DO_HARD_MUTATION @ DO_SPIRANT_MUTATION @ DO_POSTPROCESSING).string()
f5536f98c881d854fc279b81b5a6e99e4811165f
25,566
from keras.utils.data_utils import get_file from art import DATA_PATH def load_mnist(raw=False): """Loads MNIST dataset from `DATA_PATH` or downloads it if necessary. :param raw: `True` if no preprocessing should be applied to the data. Otherwise, data is normalized to 1. :type raw: `bool` :return: `...
fc661afef4062e14a90a3cbc1a837cd6f68b6039
25,567
def word_flag(*args): """ word_flag() -> flags_t Get a flags_t representing a word. """ return _ida_bytes.word_flag(*args)
765051d3c51974f24cf71a846ab3ffed4767a3d0
25,568
from typing import Mapping from sys import path def get_spark_config(predictrip_config: Mapping[str, Mapping[str, str]]) -> SparkConf: """ Create an object representing the Spark configuration we want :type predictrip_config: mapping returned by load_config containing configuration options :return: p...
cae2f7f4f384b2a05c8f66b65976fd588f15cd4a
25,569
from typing import Optional from typing import Dict from typing import Iterable from typing import Union from typing import List def get_sequence_annotations( sequence: str, allow: Optional[set] = {"H", "K", "L"}, scheme: Optional[str] = "chothia", cdr1_scheme: Optional[Dict[str, Iterable]] = { ...
3f7d74693086e7603215d912083653005cdddb5a
25,570
import stat def skew(variable=None, weights=None, data=None): """Return the asymmetry coefficient of a sample. Parameters ---------- data : pandas.DataFrame variable : array-like, str weights : array-like, str data : pandas.DataFrame Object which stores ``variable`` and ``weights`...
08be7f2e9741855b699e847307c61b14ab6b3009
25,571
def deep_initial_state(batch_size, h_size, stack_size): """ Function to make a stack of inital state for a multi-layer GRU. """ return tuple(static_initial_state(batch_size, h_size) for layer in range(stack_size))
4d6bc65d2fcb158a99a08d88c755c81ca08433f3
25,572
def create_element(pan_elem, elem_type=None)->Element: """ Find the element type and call constructor specified by it. """ etype = 'ELEMENT TYPE MISSING' if elem_type is not None: etype = elem_type elif 't' in pan_elem: etype = pan_elem['t'] elif 'pandoc-api-version' in pa...
c5507a35e7a75676e450d0f960fd3b70c873440d
25,573
def load_weights(variables, file_name): """Reshapes and loads official pretrained Yolo weights. Args: variables: A list of tf.Variable to be assigned. file_name: A name of a file containing weights. Returns: A list of assign operations. """ with open(file_name, "rb") as f: ...
3d953792ae1e13285044f40dd840fe2400f20243
25,574
def parsing_sa_class_id_response(pdu: list) -> int: """Parsing TaiSEIA class ID response protocol data.""" packet = SAInfoResponsePacket.from_pdu(pdu=pdu) if packet.service_id != SARegisterServiceIDEnum.READ_CLASS_ID: raise ValueError(f'pdu service id invalid, {pdu}') return int.from_bytes(packe...
e55c6e7041349f036babfd7e9699bfcfe1ff5dea
25,575
def wrr(self) -> int: """ Name: Write ROM port. Function: The content of the accumulator is transferred to the ROM output port of the previously selected ROM chip. The data is available on the output pins until a new WRR is execute...
a019f176bba0e50d73906abd8a20862c4993b75f
25,576
def convert_to_signed_int_32_bit(hex_str): """ Utility function to convert a hex string into a 32 bit signed hex integer value :param hex_str: hex String :return: signed 32 bit integer """ val = int(hex_str, 16) if val > 0x7FFFFFFF: val = ((val+0x80000000) & 0xFFFFFFFF) - 0x80000000 ...
f8d39b20475c30f162948167f8534e367d9c58e8
25,577
def parent_node(max_child_node, max_parent_node): """ Parents child node into parent node hierarchy :param max_child_node: MaxPlus.INode :param max_parent_node: MaxPlus.INode """ max_child_node.SetParent(max_parent_node) return max_child_node
1a54d4c485e61361633165da0f05c8f871296ae6
25,578
import getpass import re import logging import sys def get_user(): """从终端获取用户输入的QQ号及密码""" username = input('please input QQ number: ').strip() if not re.match(r'^[1-9][0-9]{4,9}$', username): logging.error('\033[31mQQ number is wrong!\033[0m') sys.exit(1) password = getpass.getpass('p...
766e8332ea0bed1b793ba80cbf42a43bd54fb800
25,579
import tensorflow as tf import torch def to_numpy_or_python_type(tensors): """Converts a structure of `Tensor`s to `NumPy` arrays or Python scalar types. For each tensor, it calls `tensor.numpy()`. If the result is a scalar value, it converts it to a Python type, such as a float or int, by calling `r...
34ea32fb2cf4fe8e45c429139876e7f1afc9f794
25,580
def _get_flow(args): """Ensure the same flow is used in hello world example and system test.""" return ( Flow(cors=True) .add(uses=MyTransformer, replicas=args.replicas) .add(uses=MyIndexer, workspace=args.workdir) )
625164c400f420cbb255cfdaa32f79c4862e23ea
25,581
def get_group_id( client: AlgodClient, txids: list ) -> list: """ Gets Group IDs from Transaction IDs :param client: an AlgodClient (GET) :param txids: Transaction IDs :return: gids - Group IDs """ # Get Group IDs gids = [] print("Getting gids...") try: w...
937b29f6b482ed1e62612a07cc80c17c6737c143
25,582
import logging import tqdm import multiprocessing def _simple_proc(st, sampling_rate=10, njobs=1): """ A parallel version of `_proc`, i.e., Basic processing including downsampling, detrend, and demean. :param st: an obspy stream :param sampling_rate: expected sampling rate :param njobs: number of...
aa24340d0d43ad8f6c042ed5e04bc94f2ec28cc3
25,583
from datetime import datetime def closing_time(date=datetime.date.today()): """ Get closing time of the current date. """ return datetime.time(13, 0) if date in nyse_close_early_dates(date.year) else datetime.time(16, 0)
40670512dbebfe65c3eb2b2790881fc91415aa40
25,584
def cos_fp16(x: tf.Tensor) -> tf.Tensor: """Run cos(x) in FP16, first running mod(x, 2*pi) for range safety.""" if x.dtype == tf.float16: return tf.cos(x) x_16 = tf.cast(tf.mod(x, 2 * np.pi), tf.float16) return tf.cos(x_16)
3212eb19e43fa733490d2cfcfffcc0094715022b
25,585
from typing import Callable def is_documented_by(original: Callable) -> Callable[[_F], _F]: """ Decorator to set the docstring of the ``target`` function to that of the ``original`` function. This may be useful for subclasses or wrappers that use the same arguments. :param original: """ def wrapper(target: _...
acd582112371ccfffd53762546415353abbd3129
25,586
def check_if_bst(root, min, max): """Given a binary tree, check if it follows binary search tree property To start off, run `check_if_bst(BT.root, -math.inf, math.inf)`""" if root == None: return True if root.key < min or root.key >= max: return False return check_if_bst(root.left,...
1bb4b601ef548aec9a4ab2cf5242bc5875c587a2
25,587
import os import glob def assert_widget_image(tmpdir, widget, filename, fail_now=True): """ Render an image from the given WWT widget and assert that it matches an expected version. The expected version might vary depending on the platform and/or OpenGL renderer, so we allow for multiple references an...
6ffe5b6f573744e702af5a2ccf3ef69d1d9b7102
25,588
from typing import Union import pathlib from typing import Sequence from typing import Any import torchvision def create_video_file( root: Union[pathlib.Path, str], name: Union[pathlib.Path, str], size: Union[Sequence[int], int] = (1, 3, 10, 10), fps: float = 25, **kwargs: Any, ) -> pathlib.Path: ...
f11748ae86a80a5f4d9c859c313837fac7effa32
25,589
def aggregate(collection, pipeline): """Executes an aggregation on a collection. Args: collection: a `pymongo.collection.Collection` or `motor.motor_tornado.MotorCollection` pipeline: a MongoDB aggregation pipeline Returns: a `pymongo.command_cursor.CommandCursor` or ...
03ea889ea23fb81c6a329ee270df2ac253e90d69
25,590
def decryptAES(key, data, mode=2): """decrypt data with aes key""" return aes.decryptData(key, data, mode)
30f5b4173a8ed388a13481a2fd41293cd2304b21
25,591
import requests def __ipv6_safe_get(endpoint: str, addr: str) -> str: """HTTP GET from endpoint with IPv6-safe Host: header Args: endpoint: The endpoint path starting with / addr: full address (IPV6 or IPv4) of server Notes: * This is needed because the Py...
adb1c7c2300e9e41049a9eda957f264322095d9c
25,592
def format_advertisement(data): """ format advertisement data and scan response data. """ resolve_dict = { # FLAGS AD type st_constant.AD_TYPE_FLAGS: 'FLAGS', # Service UUID AD types st_constant.AD_TYPE_16_BIT_SERV_UUID: '16_BIT_SERV_UUID', st_constant.AD_TYPE_16_BIT_SERV...
a2b2740c45debe6c801ac80d99c8ed2b4537c205
25,593
def is_dicom_file(path): """Check if the given path appears to be a dicom file. Only looks at the extension, not the contents. Args: path (str): The path to the dicom file Returns: bool: True if the file appears to be a dicom file """ path = path.lower() for ext in DICOM_E...
2bd20b0f9bf40db24e9c6df4591127f59d07f882
25,594
import math def build_graph(df_list, sens='ST', top=410, min_sens=0.01, edge_cutoff=0.0, edge_width=150, log=False): """ Initializes and constructs a graph where vertices are the parameters selected from the first dataframe in 'df_list', subject to the constraints set by 'sens', 'top',...
b17b3f57ab21df0117e61a12005f401f81620368
25,595
def ranking_scores(prng=None, mix=False, permute=False, gamma=0.01, beta=5., N=100, l=1, means=None, stds=None): """ Generate the ranking scores. Parameters ---------- prng : random generator container Seed for the random number generator. mix : bool ...
40801599ab67d852740d5219d22debdbed91de39
25,596
def calculate_direction(G, cutoff, normalize=True): """ Calculate direction for entire network Parameters ---------- G : nx.graph Fault network cutoff : int, float Cutoff distance for direction normalize : bolean Normalize direction (default: True) Returns ...
9b64e0e8226579728f76ab510e672372cb708338
25,597
from datetime import datetime def generateVtBar(row): """生成K线""" bar = VtBarData() bar.symbol = row['code'] bar.exchange = '' bar.vtSymbol = bar.symbol bar.open = row['open'] bar.high = row['high'] bar.low = row['low'] bar.close = row['close'] bar.volume = row['volume'] ...
8431b313927692743d727ef9225e33899cc6c916
25,598
async def is_valid_channel(ctx, channel_name): """ TODO: Use discord.py converters instead of is_valid_channel check """ matched_channels = [ channel for channel in ctx.guild.channels if channel.name == channel_name ] if len(matched_channels) == 0: await ctx.send( "Ca...
46fd29fff440151e9478c8a5bd9cad9d8c04edd3
25,599