content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import math def _get_process_num_examples(builder, split, process_batch_size, process_index, process_count, drop_remainder): """Returns the number of examples in a given process's split.""" process_split = _get_process_split( split, process_index=process_index, proc...
a0621a6146e919db78b0ff5e7a5ae6d3c1bb68a6
3,656,513
def export_python_function(earth_model): """ Exports model as a pure python function, with no numpy/scipy/sklearn dependencies. :param earth_model: Trained pyearth model :return: A function that accepts an iterator over examples, and returns an iterator over transformed examples """ i = 0 ac...
593d8cf9f1156359f2276f0481e02a2d00d8ffde
3,656,514
def ehi(data, thr_95, axis=0, keepdims=False): """ Calculate Excessive Heat Index (EHI). Parameters ---------- data: list/array 1D/2D array of daily temperature timeseries thr_95: float 95th percentile daily mean value from climatology axis: int The axis along which ...
b56166dc070c9f44ce0d8197526c09ba2f95995c
3,656,515
def get_disable_migration_module(): """ get disable migration """ class DisableMigration: def __contains__(self, item): return True def __getitem__(self, item): return None return DisableMigration()
d44a26c5e597f23dbc2434488baf54ebccc5010c
3,656,517
def __sbox_bytes(data, sbox): """S-Box substitution of a list of bytes""" return [__sbox_single_byte(byte, sbox) for byte in data]
db4999ada745c07127d9eff66841877a157839ec
3,656,519
def load_config_with_kwargs(cls, kwargs): """Takes a marshmallow class and dict of parameter values and appropriately instantiantes the schema.""" assert_is_a_marshmallow_class(cls) schema = cls.Schema() fields = schema.fields.keys() return load_config(cls, **{k: v for k, v in kwargs.items() if k in...
9058becb8ae387ad012554ff0afe7ac5fcbf62f7
3,656,520
def split_rows(sentences, column_names): """ Creates a list of sentence where each sentence is a list of lines Each line is a dictionary of columns :param sentences: :param column_names: :return: """ new_sentences = [] root_values = ['0', 'ROOT', 'ROOT', 'ROOT', 'ROOT', 'ROOT', '0', ...
444733a9c169bedae8dc0045cd696cafed7085e2
3,656,521
def _rollup_date(dts, interval=None): """format date/time string based on interval spec'd for summation For Daily, it returns just the date. No time or timezeone. For Hourly, it returns an ISO-8061 datetime range. This provides previously missing clarity around whether the rainfall amount shown was fo...
12f74d9becfa52c626d33174cb628dc9e0112c07
3,656,523
def offset_compensation(time_signal): """ Offset compensation filter. """ return lfilter([1., -1], [1., -0.999], time_signal)
0fc423646071dc07bf88f88698f3248fa302a41e
3,656,524
from typing import Callable from re import T from typing import cast def _alias(default: Callable) -> Callable[[T], T]: """ Decorator which re-assigns a function `_f` to point to `default` instead. Since global function calls in Python are somewhat expensive, this is mainly done to reduce a bit of ove...
f286472a7f14428ea5243d54a671b9d3d743c9ef
3,656,526
def test_image(filename): """ Return the absolute path to image file having *filename* in test_files directory. """ return absjoin(thisdir, 'test_files', filename)
bda20e51a495e56f8ebf373819e60ebdea3da535
3,656,527
import difflib def menu( ticker: str, start: str, interval: str, stock: pd.DataFrame, ): """Sector and Industry Analysis Menu""" sia_controller = SectorIndustryAnalysisController(ticker, start, interval, stock) sia_controller.call_help(None) while True: # Get input command fro...
5c3d13d292525abdb5c7f98a2467274c2172cf8f
3,656,528
def fname_template(orun, detname, ofname, nevts, tsec=None, tnsec=None): """Replaces parts of the file name specified as #src, #exp, #run, #evts, #type, #date, #time, #fid, #sec, #nsec with actual values """ template = replace(ofname, '#src', detname) template = replace(template, '#exp',...
7f38b638d89a7f99ab36b4e08369cfc7f22bb575
3,656,529
def opt_checked(method): """Like `@checked`, but it is legal to not specify the value. In this case, the special `Unset` value is passed to the validation function. Storing `Unset` causes the key to not be emitted during serialization.""" return Checked(method.__name__, method.__doc__, method, True)
5d34db8fcc602dc51d69c128a1855eef44c81453
3,656,530
from datetime import datetime def _metadata(case_study): """Collect metadata in a dictionnary.""" return { 'creation_date': datetime.strftime(datetime.now(), '%c'), 'imagery': case_study.imagery, 'latitude': case_study.lat, 'longitude': case_study.lon, 'area_of_interest...
eb16892135326662029fe568922f2871f016090e
3,656,531
def CoP_constraints_ds( m, foot_angles, next_support_foot_pos, stateX, stateY, N=16, dt=0.1, h=1.0, g=9.81, tPf=8, ): """ INPUTS m (int): remaining time steps in current foot step; foot_angles ([N, 1] vector): containing the orientations in radians of the foot...
647e9313b79523ae41ab47a61501c1b356d43785
3,656,532
import io def HARRIS(img_path): """ extract HARR features :param img_path: :return: :Version:1.0 """ img = io.imread(img_path) img = skimage.color.rgb2gray(img) img = (img - np.mean(img)) / np.std(img) feature = corner_harris(img, method='k', k=0.05, eps=1e-06, sigma=1) re...
5c11c9e5b2947b0ddeb2e1780d11be4020fe53a4
3,656,533
def http_req(blink, url='http://example.com', data=None, headers=None, reqtype='get', stream=False, json_resp=True, is_retry=False): """ Perform server requests and check if reauthorization neccessary. :param blink: Blink instance :param url: URL to perform request :param data: Data to...
0596f82752292216235e9d9f3b14bb01f053d0d7
3,656,535
def make_dataset(path, seq_length, mem_length, local_rank, lazy=False, xl_style=False, shuffle=True, split=None, tokenizer=None, tokenizer_type='CharacterLevelTokenizer', tokenizer_model_path=None, vocab_size=None, model_type='bpe', pad_token=0, character_converage=1.0, ...
419e50d3dab13d9aa1f096b99a598c52441bb2ae
3,656,536
import re def fix_reference_name(name, blacklist=None): """Return a syntax-valid Python reference name from an arbitrary name""" name = "".join(re.split(r'[^0-9a-zA-Z_]', name)) while name and not re.match(r'([a-zA-Z]+[0-9a-zA-Z_]*)$', name): if not re.match(r'[a-zA-Z]', name[0]): name...
2f1a291fc7ac9816bc2620fceeeaf90a1bb3fd4a
3,656,537
from hybridq.gate.gate import _available_gates def get_available_gates() -> tuple[str, ...]: """ Return available gates. """ return tuple(_available_gates)
f4d9e8d617675174f97d7d1cc3d6ea8bdadab725
3,656,540
def main(): """ Entry point Collect all reviews from the file system (FS) & Dump it into JSON representation back to the FS Returns: int: The status code """ collector = Collector() return collector.collect()
d6d15227fe37522357a3f1706cf446026e277a32
3,656,541
def __parse_tokens(sentence: spacy.tokens.Doc) -> ParsedUniversalDependencies: """Parses parts of speech from the provided tokens.""" #tokenize # remove the stopwards, convert to lowercase #bi/n-grams adj = __get_word_by_ud_pos(sentence, "ADJ") adp = __get_word_by_ud_pos(sentence, "ADP") adv...
86553239aaac9d89203722f3853989ba0f95b8e3
3,656,542
from datetime import datetime def main(): """ In this main function, we connect to the database, and we create position table and intern table and after that we create new position and new interns and insert the data into the position/intern table """ database = r"interns.db" sql_drop_posi...
89b88d681b4f4eaeada0a8e8de5a3dadad1ddd15
3,656,543
from typing import Tuple def parse_date(month: int, day: int) -> Tuple[int, int, int]: """Parse a date given month and day only and convert to a tuple. Args: month (int): 1-index month value (e.g. 1 for January) day (int): a day of the month Returns: Tuple[int, int, int]: (ye...
d9ebb40061c14c9a2b1336465921cea0d5c756a8
3,656,544
def usgs_perlite_parse(*, df_list, source, year, **_): """ Combine, parse, and format the provided dataframes :param df_list: list of dataframes to concat and format :param source: source :param year: year :return: df, parsed and partially formatted to flowbyactivity specifications "...
8b9b1dcf3312cb59f5a27873e791c4bc744599bc
3,656,545
import warnings def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): # token from https://github.com/bioinf-jku/TTUR/blob/master/fid.py """Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is ...
0f22ce0a99e9b8f2ffca7af4a190c020f376ce8c
3,656,546
def _svdvals_eig(x): # pragma: no cover """SVD-decomposition via eigen, but return singular values only. """ if x.shape[0] > x.shape[1]: s2 = np.linalg.eigvalsh(dag(x) @ x) else: s2 = np.linalg.eigvalsh(x @ dag(x)) return s2**0.5
af47405994cf8fa1504fcb898b7621483eb1e346
3,656,547
def get_3d_object_section(target_object): """Returns 3D section includes given object like stl. """ target_object = target_object.flatten() x_min = min(target_object[0::3]) x_max = max(target_object[0::3]) y_min = min(target_object[1::3]) y_max = max(target_object[1::3]) z_min = min(tar...
e11d62ad06ada005d16803b2f440ac700e272599
3,656,548
def make_row(filename, num_cols, col_names): """ Given a genome file, create and return a row of kmer counts to be inerted into the mer matrix. """ # Filepath thefile = str(filename[0]) # Get the genome id from the filepath genomeid = filename[0].split('/')[-1] genomeid = genomeid.s...
59ed16c4a19da95145ed56164bc35ef24bc7f6bc
3,656,550
def analytic_overlap_NM( DQ: float, w1: float, w2: float, n1: int, n2: int ) -> float: """Compute the overlap between two displaced harmonic oscillators. This function computes the overlap integral between two harmonic oscillators with frequencies w1, w2 that are dis...
f0eba159f1bfb3fd05b1a825170e03e02587ef32
3,656,551
def init_manager(mocker): """Fixture to initialize a style constant.""" mocker.patch.object(manager.StyleManager, "__init__", lambda x: None) def _create(): return manager.StyleManager() return _create
da7838352c0a8c13acfcd0d345f78e329978409c
3,656,552
def GaussLegendre(f, n): """Gauss-Legendre integration on [-1, 1] with n points.""" x, w = numint.GaussLegendre(n) I = np.dot(f(x), w) return I
73fcd257e92852b56fcec7d0f21cbbcf87afdb51
3,656,553
from typing import List from typing import Dict from typing import OrderedDict def directory_item_groups( items: List[Item], level: int ) -> Dict[str, List[Item]]: """Split items into groups per directory at the given level. The level is relative to the root directory, which is at level 0. """ mod...
2a8e8138097ad48417f9988059a0ed19d63e4877
3,656,554
def mergeSort(x): """ Function to sort an array using merge sort algorithm """ if len(x) == 0 or len(x) == 1: return x else: middle = len(x)//2 a = mergeSort(x[:middle]) b = mergeSort(x[middle:]) return merge(a,b)
9187209cd9e679c790d0cddc18d58e6edc3e6d3a
3,656,555
from typing import Union from typing import Optional from typing import Dict from typing import Any async def join( db, query: Union[dict, str], document: Optional[Dict[str, Any]] = None, session: Optional[AsyncIOMotorClientSession] = None, ) -> Optional[Dict[str, Any]]: """ Join the otu assoc...
d01dc90855692a149a279fbad9b8777d4a850a7d
3,656,556
import time import networkx import math def cp_solve(V, E, lb, ub, col_cov, cuts=[], tl=999999): """Solves a partial problem with a CP model. Args: V: List of vertices (columns). E: List of edges (if a transition between two columns is allowed). col_cov: Matrix of the zone coverages of ...
6ad8ca02fcf119192e3aad4881a4eb9e0adf30d0
3,656,557
def file_exists(path: Text): """ Returns true if file exists at path. Args: path (str): Local path in filesystem. """ return file_io.file_exists_v2(path)
9d9acf36ad0276a4fa440a54ed859b24e6bfee4e
3,656,558
import requests import json def _get_page_num_detail(): """ 东方财富网-数据中心-特色数据-机构调研-机构调研详细 http://data.eastmoney.com/jgdy/xx.html :return: int 获取 机构调研详细 的总页数 """ url = "http://data.eastmoney.com/DataCenter_V3/jgdy/xx.ashx" params = { "pagesize": "5000", "page": "1", "j...
84c32485637cb481f1ebe6fe05609e5b545daece
3,656,559
def freeze_session( session, keep_var_names=None, output_names=None, clear_devices=True): """ Freezes the state of a session into a pruned computation graph. """ graph = session.graph with graph.as_default(): freeze_var_names = list(set(v.op.name for v in tf.g...
ad8335110c139b73fb0c5cebb56dbdeea702a751
3,656,560
def send_mail(subject, body, recipient_list, bcc_list=None, from_email=None, connection=None, attachments=None, fail_silently=False, headers=None, cc_list=None, dc1_settings=None, content_subtype=None): """ Like https://docs.djangoproject.com/en/dev/topics/email/#send-mail Attachment is a list...
36389b7f7e0906aa92ce06c66c4f51faa2643e31
3,656,561
def distinct_by_t(func): """ Transformation for Sequence.distinct_by :param func: distinct_by function :return: transformation """ def distinct_by(sequence): distinct_lookup = {} for element in sequence: key = func(element) if key not in distinct_lookup: ...
3e2811b9f1b69b5c45f65a561b7f67ae477c8825
3,656,562
def _get_partition_info(freq_unit): """ 根据平台单位获取tdw的单位和格式 :param freq_unit: 周期单位 :return: tdw周期单位, 格式 """ if freq_unit == "m": # 分钟任务 cycle_unit = "I" partition_value = "" elif freq_unit == "H": # 小时任务 cycle_unit = "H" partition_value = "YYYYMM...
1f7df3364a21018daa8d3a61507ee59c467c8ffc
3,656,564
from typing import Any def metadata_property(k: str) -> property: """ Make metadata fields available directly on a base class. """ def getter(self: MetadataClass) -> Any: return getattr(self.metadata, k) def setter(self: MetadataClass, v: Any) -> None: return setattr(self.metadat...
22d3ab3c8a7029564083a6ba544acd69f2ee5491
3,656,565
import torch def adjust_contrast(img, contrast_factor): """Adjust contrast of an RGB image. Args: img (Tensor): Image to be adjusted. contrast_factor (float): How much to adjust the contrast. Can be any non negative number. 0 gives a solid gray image, 1 gives the origi...
740c68fe269229329cd37d25424178a74f5ac7fc
3,656,566
def license_wtfpl(): """ Create a license object called WTF License. """ return mixer.blend(cc.License, license_name="WTF License")
d202d605fe84556c553fdc7cf70c5815eb1dbee4
3,656,567
import copy def _add_embedding_column_map_fn( k_v, original_example_key, delete_audio_from_output, audio_key, label_key, speaker_id_key): """Combine a dictionary of named embeddings with a tf.train.Example.""" k, v_dict = k_v if original_example_key not in v_dict: raise ValueError( ...
710fd658b0f1d830c8e4e97d473b02f54a0d4414
3,656,568
def modelf(input_shape): """ Function creating the model's graph in Keras. Argument: input_shape -- shape of the model's input data (using Keras conventions) Returns: model -- Keras model instance """ X_input = Input(shape = input_shape) ### START CODE HERE ### ...
d8beaf7335e19c66ea3913ed019647d9e42f92d1
3,656,569
def get_mbed_official_psa_release(target=None): """ Creates a list of PSA targets with default toolchain and artifact delivery directory. :param target: Ask for specific target, None for all targets. :return: List of tuples (target, toolchain, delivery directory). """ psa_targets_release_li...
0f260c1d57b0d21d911fcd6998fadee0791600de
3,656,570
def match_l2(X, Y, match_rows=False, normalize=True): """Return the minimum Frobenius distance between X and Y over permutations of columns (or rows).""" res = _match_factors(X, Y, l2_similarity, match_rows) res['score'] = np.sqrt(-res['score']) if normalize: res['score'] = res['score'] / np.lin...
181ecde4c0837b69f7a37287bcf9e768fdaa3e58
3,656,571
import time import scipy def doNMFDriedger(V, W, L, r = 7, p = 10, c = 3, plotfn = None, plotfnw = None): """ Implement the technique from "Let It Bee-Towards NMF-Inspired Audio Mosaicing" :param V: M x N target matrix :param W: An M x K matrix of template sounds in some time order\ along ...
3b3b0fe9388992bdd87cfa6b4cb0748f4502adc7
3,656,572
def extract_red(image): """ Returns the red channel of the input image. It is highly recommended to make a copy of the input image in order to avoid modifying the original array. You can do this by calling: temp_image = np.copy(image) Args: image (numpy.array): Input RGB (BGR in OpenCV) image. ...
0f591099e439a038ef8e75d65e4eb26c200018d0
3,656,573
def _cleaned_data_to_key(cleaned_data): """ Return a tuple representing a unique key for the cleaned data of an InteractionCSVRowForm. """ # As an optimisation we could just track the pk for model instances, # but that is omitted for simplicity key = tuple(cleaned_data.get(field) for field in DU...
aa08e0cafd0ac4ba3749db65208655dc51671997
3,656,574
def schedule_for_cleanup(request, syn): """Returns a closure that takes an item that should be scheduled for cleanup. The cleanup will occur after the module tests finish to limit the residue left behind if a test session should be prematurely aborted for any reason.""" items = [] def _append_clea...
ccbdba1a1f8dea0f13e5717d0743739d599e22e6
3,656,575
import base64 def unpickle_context(content, pattern=None): """ Unpickle the context from the given content string or return None. """ pickle = get_pickle() if pattern is None: pattern = pickled_context_re match = pattern.search(content) if match: return pickle.loads(base64....
87fa831b038329313364d512107129f69db136ad
3,656,576
def ask_openid(request, openid_url, redirect_to, on_failure=None, sreg_request=None): """ basic function to ask openid and return response """ on_failure = on_failure or signin_failure trust_root = getattr( settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/' ) if xri.ide...
bb5deefc32d1c4253d518eeead34b290e028a051
3,656,577
import torch def get_accuracy_ANIL(logits, targets): """Compute the accuracy (after adaptation) of MAML on the test/query points Parameters ---------- logits : `torch.FloatTensor` instance Outputs/logits of the model on the query points. This tensor has shape `(num_examples, num_classe...
2ab61284da6d9cd96c066061823570d64567e9f3
3,656,578
import logging def stream_logger(): """ sets up the logger for the Simpyl object to log to the output """ logger = logging.Logger('stream_handler') handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(asctime)s %(message)s')) logger.addHandler(handler) return logger
45f5af00a0006cc8155bb4a134cce531e51e646a
3,656,579
def sql_coordinate_frame_lookup_key(bosslet_config, coordinate_frame): """ Get the lookup key that identifies the coordinate fram specified. Args: bosslet_config (BossConfiguration): Bosslet configuration object coordinate_frame: Identifies coordinate frame. Returns: coordinate...
8bf7db01b171e13b0066a806eb097dec4a59c04e
3,656,580
def entry_from_resource(resource, client, loggers): """Detect correct entry type from resource and instantiate. :type resource: dict :param resource: One entry resource from API response. :type client: :class:`~google.cloud.logging.client.Client` :param client: Client that owns the log entry. ...
0519ad63c11e04ca890288953440272de224b9db
3,656,581
def make_preprocesser(training_data): """ Constructs a preprocessing function ready to apply to new dataframes. Crucially, the interpolating that is done based on the training data set is remembered so it can be applied to test datasets (e.g the mean age that is used to fill in missing values for '...
480ba5b02e5347e768bd5b2cdbc8b19af1ddee8c
3,656,582
def get_breakeven_prob(predicted, threshold = 0): """ This function calculated the probability of a stock being above a certain threshhold, which can be defined as a value (final stock price) or return rate (percentage change) """ predicted0 = predicted.iloc[0,0] predicted = predicted.iloc[-1] p...
a1cededbe7a0fbe7ffe19e9b873f55c8ce369590
3,656,583
def trim_whitespace(sub_map, df, source_col, op_col): """Trims whitespace on all values in the column""" df[op_col] = df[op_col].transform( lambda x: x.strip() if not pd.isnull(x) else x) return df
649a48cbb9246d4842555b5a21bc4d638a00ca00
3,656,584
from re import A from re import T def beneficiary(): """ RESTful CRUD controller """ # Normally only used in Report # - make changes as component of Project s3db.configure("project_beneficiary", deletable = False, editable = False, insertable =...
ec34dd0989154bcfe2ace8506fe1cbe9c1ba9c49
3,656,585
def setup(args): """ Create configs and perform basic setups. """ cfg = get_cfg() #cfg.merge_from_file(args.config_file) #cfg.merge_from_file(model_zoo.get_config_file("/data/mostertrij/tridentnet/detectron2/configs/COCO-Detection/my_script_faster_rcnn_X_101_32x8d_FPN_3x.yaml")) cfg.merge_fr...
a3053945cd6680c220fe8ea87189943c44558d8d
3,656,586
def get_distinct_quotation_uid(*args, **kwargs): """ 获取用户 :param args: :param kwargs: :return: List """ field = 'uid' return map(lambda x: getattr(x, field), db_instance.get_distinct_field(Quotation, field, *args, **kwargs))
5a8fe7252f6ac233b69e57c0baac0f1f2d3f51ff
3,656,587
import pathlib def present_from(ref: pathlib.Path, obs: pathlib.Path) -> pathlib.Path: """Build a somehow least surprising difference folder from ref and obs.""" ref_code = ref.parts[-1] if obs.is_file(): return pathlib.Path(*obs.parts[:-1], f'diff-of-{obs.parts[-1]}') present = pathlib.Path(...
59ae1eefaeacc9ddfac773c0c88974b98757d4a2
3,656,588
def dataQ_feeding(filename_queue, feat_dim, seq_len): """ Reads and parse the examples from alignment dataset Args: filename_queue: A queue of strings with the filenames to read from. Returns: An object representing a single example, with the following fields: MFCC sequence: 200 * 39 d...
23d3e81bdd266f6cebe9bdff2160c4b7294e648c
3,656,589
def dummy_backend(_, **kwargs): """ Dummy backend always returning stats with 0 """ return _default_statement()
875adb50540029022b28de6388738d1e5ba01e30
3,656,590
def comp_mass(self): """Compute the mass of the Frame Parameters ---------- self : Frame A Frame object Returns ------- Mfra: float Mass of the Frame [kg] """ Vfra = self.comp_volume() # Mass computation return Vfra * self.mat_type.struct.rho
b78ef02f045c1f624b3277ec3e358921b3ea5c02
3,656,591
def write_DS9reg(x, y, filename=None, coord='IMAGE', ptype='x', size=20, c='green', tag='all', width=1, text=None): """Write a region file for ds9 for a list of coordinates. Taken from Neil Crighton's barak.io Parameters ---------- x, y : arrays of floats, shape (N,) The c...
9e2c67c8a681ba7abdd55e7f456079b32ed50688
3,656,592
def checkInputDataValid(lstX:list=None,lstY:list=None,f:object=None)->(int,tuple): """ :param lstX: :param lstY: :param f: :return: int, (int,list, int,int) """ ret=-1 rettuple=(-1,[],-1,-1) if lstX is None or lstY is None: msg = "No input lists of arrays" msg2log(No...
daacee0ee3803c02c04fe2b7213c6f8d408b39f6
3,656,593
def parseManualTree(node): """Parses a tree of the manual Main_Page and returns it through a list containing tuples: [(title, href, [(title, href, [...]), ...]), ...]""" if node.nodeType != Node.ELEMENT_NODE: return [] result = [] lastadded = None for e in node.childNodes: if e.nodeType ...
6b62e9ad3b3ef4f3a0c6c60a931f1f2e940fe0f9
3,656,594
from typing import Union from typing import List from typing import Dict from typing import Optional from typing import Tuple import tqdm def validation_by_method(mapping_input: Union[List, Dict[str, List]], graph: nx.Graph, kernel: Matrix, k:...
b7ce9e72af55dc6d111948cb393f5e07b7fedd68
3,656,595
def get_about_agent(): """ This method returns general information of the agent, like the name and the about. Args: @param: token: Authentication token. """ data = request.get_json() if "token" in data: channel = get_channel_id(data["token"]) if channel is not None: ...
ca4301a9de5d4cb711892a221d4c984489c1e329
3,656,596
def RZ(angle, invert): """Return numpy array with rotation gate around Z axis.""" gate = np.zeros(4, dtype=complex).reshape(2, 2) if not invert: gate[0, 0] = np.cos(-angle/2) + np.sin(-angle/2) * 1j gate[1, 1] = np.cos(angle/2) + np.sin(angle/2) * 1j else: gate[0, 0] = np.cos(-an...
d99839fa49d92edea8d98653fd7a38861e6f49d8
3,656,598
def _create_unicode(code: str) -> str: """ Добавление экранизирующего юникод кода перед кодом цвета :param code: Код, приоритетно ascii escape color code :return: """ return u'\u001b[{}m'.format(code)
523973766d4f18daca8870e641ac77967b715532
3,656,599
def compact_axis_angle_from_matrix(R): """Compute compact axis-angle from rotation matrix. This operation is called logarithmic map. Note that there are two possible solutions for the rotation axis when the angle is 180 degrees (pi). We usually assume active rotations. Parameters ---------- ...
a7493a5ed1c622b9cbec6e9f0771e62f7f4712e2
3,656,600
def _generate_IPRange(Range): """ IP range to CIDR and IPNetwork type Args: Range: IP range Returns: an array with CIDRs """ if len(Range.rsplit('.')) == 7 and '-' in Range and '/' not in Range: if len(Range.rsplit('-')) == 2: start_ip, stop_ip = Range.rspli...
d86f8db8e87313b12f35669ee25cc3f3d229c631
3,656,601
def is_dict_homogeneous(data): """Returns True for homogeneous, False for heterogeneous. An empty dict is homogeneous. ndarray behaves like collection for this purpose. """ if len(data) == 0: return True k0, v0 = next(iter(data.items())) ktype0 = type(k0) vtype0 = type(v0) i...
921e66639cd6a8584e99e14852158594b1001ef9
3,656,602
from typing import Union from typing import Callable from re import T from typing import Generator from typing import Any def translate(item: Union[Callable[P, T], Request]) -> Union[Generator[Any, Any, None], Callable[P, T]]: """Override current language with one from language header or 'lang' parameter. Can...
5042cc77efb1477444f8f9611055fb3e183cf3d3
3,656,603
def get_all(isamAppliance, check_mode=False, force=False, ignore_error=False): """ Retrieving the current runtime template files directory contents """ return isamAppliance.invoke_get("Retrieving the current runtime template files directory contents", "/mga/template_f...
9ff291b63471b57b110885c35939c8afe3d2f0d8
3,656,604
def main(args, out, err): """ This wraps GURepair's real main function so that we can handle exceptions and trigger our own exit commands. This is the entry point that should be used if you want to use this file as a module rather than as a script. """ cleanUpHandler = BatchCaller(args.ve...
c506306a93804ab60c1a6805e9c53a0fd9dd7cfd
3,656,607
def generateLouvainCluster(edgeList): """ Louvain Clustering using igraph """ Gtmp = nx.Graph() Gtmp.add_weighted_edges_from(edgeList) W = nx.adjacency_matrix(Gtmp) W = W.todense() graph = Graph.Weighted_Adjacency( W.tolist(), mode=ADJ_UNDIRECTED, attr="weight", loops=False) # ig...
c171474bdd81456cbbc488b0a8cb826f881419ec
3,656,609
def exprvars(name, *dims): """Return a multi-dimensional array of expression variables. The *name* argument is passed directly to the :func:`pyeda.boolalg.expr.exprvar` function, and may be either a ``str`` or tuple of ``str``. The variadic *dims* input is a sequence of dimension specs. A dime...
6b65872029de938d37c9e968f696587e2a03ff8c
3,656,610
def cell_segmenter(im, thresh='otsu', radius=20.0, image_mode='phase', area_bounds=(0,1e7), ecc_bounds=(0, 1)): """ This function segments a given image via thresholding and returns a labeled segmentation mask. Parameters ---------- im : 2d-array Image to be segmente...
f9a8fa3c29cbb213ed67c3df93106a81f53ae985
3,656,611
from datetime import datetime def generate_report(start_date, end_date): """Generate the text report""" pgconn = get_dbconn('isuag', user='nobody') days = (end_date - start_date).days + 1 totalobs = days * 24 * 17 df = read_sql(""" SELECT station, count(*) from sm_hourly WHERE valid >= %s ...
f71b5ab58922b9018abc1868661f88c268de8f94
3,656,612
import pathlib def whole(eventfile,par_list,tbin_size,mode,ps_type,oversampling,xlims,vlines): """ Plot the entire power spectrum without any cuts to the data. eventfile - path to the event file. Will extract ObsID from this for the NICER files. par_list - A list of parameters we'd like to extract fr...
77b51cc8774bdb1b670e2a6b56a9cd65213f70de
3,656,613
def handle_postback(): """Handles a postback.""" # we need to set an Access-Control-Allow-Origin for use with the test AJAX postback sender # in normal operations this is NOT needed response.set_header('Access-Control-Allow-Origin', '*') args = request.json loan_id = args['request_token'] m...
59683921b7a21f50c2905c47c33036fd75ce54f4
3,656,614
def get_bb_bev_from_obs(dict_obs, pixor_size=128): """Input dict_obs with (B,H,W,C), return (B,H,W,3)""" vh_clas = tf.squeeze(dict_obs['vh_clas'], axis=-1) # (B,H,W,1) # vh_clas = tf.gather(vh_clas, 0, axis=-1) # (B,H,W) vh_regr = dict_obs['vh_regr'] # (B,H,W,6) decoded_reg = decode_reg(vh_regr, pixor_size...
d286ec0c3132c2dcb931cb941fd247810c0ce1cf
3,656,615
def get_hard_edges(obj): """ :param str obj: :returns: all hard edges from the given mesh in a flat list :rtype: list of str """ return [obj + '.e[' + str(i) + ']' for i, edgeInfo in enumerate(cmds.polyInfo(obj + '.e[*]', ev=True)) if edgeInfo.endswith('Hard\n')]
67de22469a38e55e88d21f1853280138795a04cb
3,656,616
def make_system(l=70): """ Making and finalizing a kwant.builder object describing the system graph of a closed, one-dimensional wire with l number of sites. """ sys = kwant.Builder() lat = kwant.lattice.chain() sys[(lat(x) for x in range(l))] = onsite sys[lat.neighbors()] = hopping return sys.finalized()
fa3d25933fd086519569cbb24ff77bf3c86c1303
3,656,617
from typing import Type from pathlib import Path from typing import Dict def _gen_test_methods_for_rule( rule: Type[CstLintRule], fixture_dir: Path, rules_package: str ) -> TestCasePrecursor: """Aggregates all of the cases inside a single CstLintRule's VALID and INVALID attributes and maps them to altered nam...
5a12d84bdcff039179ef9b9f1105e6beecccbf05
3,656,618
def evaluate_score_batch( predicted_classes=[], # list, len(num_classes), str(code) predicted_labels=[], # shape (num_examples, num_classes), T/F for each code predicted_probabilities=[], # shape (num_examples, num_classes), prob. [0-1] for each code raw_ground_truth_labels=[], # list(('dx1', 'dx2')...
314f94433704cc2986df9082a749caaf52738f08
3,656,619
import tqdm def gauss_kernel(model_cell, x, y, z, sigma=1): """ Convolute aligned pixels given coordinates `x`, `y` and values `z` with a gaussian kernel to form the final image. Parameters ---------- model_cell : :class:`~colicoords.cell.Cell` Model cell defining output shape. x : :c...
0ff61121fbf330e3e15862b82b0929ae3b8748f9
3,656,621
def get_configs_from_multiple_files(): """Reads training configuration from multiple config files. Reads the training config from the following files: model_config: Read from --model_config_path train_config: Read from --train_config_path input_config: Read from --input_config_path Returns: mode...
4f561235568667a6fe71d77c23769ea8878ebe20
3,656,622
def line_to_numbers(line: str) -> t.List[int]: """Split a spreadsneet line into a list of numbers. raises: ValueError """ return list(map(int, line.split()))
fce9af5e1c213fd91f0edf8d7fa5877f15374908
3,656,623
def bits_to_amps(bits): """helper function to convert raw data from usb device to amps""" return bits*BITS_TO_AMPS_SLOPE + BITS_TO_AMPS_Y_INTERCEPT
5653582987b6a7924c11f037badc1a61541c6ca2
3,656,624
def time_difference(t_early, t_later): """ Compute the time difference between t_early and t_later Parameters: t_early: np.datetime64, list or pandas series. t_later: np.datetime64, list or pandas series. """ if type(t_early) == list: t1 = np.array(t_early) elif type(t_early) ==...
0d4e6bac3aed2e5a2848c4289dadc92120a4f7a1
3,656,627
def conv2d_block(input_tensor, n_filters, kernel_size=3, batchnorm=True): """ Convolutional block with two convolutions followed by batch normalisation (if True) and with ReLU activations. input_tensor: A tensor. Input tensor on which the convolutional block acts. n_filters: An integer. Number of filters in...
8bb435ed1e091fff26d49290a8ca6d0c9c12ec67
3,656,628