content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def invert_color(color: str, *, black_or_white: bool = False) -> str: """Return a color with opposite red, green and blue values. Example: ``invert_color('white')`` is ``'#000000'`` (black). This function uses tkinter for converting the color to RGB. That's why a tkinter root window must have been cre...
cf6a84957489cba046aebc01457bfd6453bc90b6
2,070
def pcaImageCube(ref, mask = None, pcNum = None, cube=True, ref3D=True, outputEval = False): """Principal Component Analysis, Input: ref: Cube of references, 3D; if ref3D==False, 2D (Flattened and Normalized, with maksked region excluded.) mask: mask, 2D or 1D; pcNum: how...
96a05ef8fd6a618af91903b9c0fc9fc49cfd8130
2,071
def get_cross_kerr_table(epr, swp_variable, numeric): """ Function to re-organize the cross-Kerr results once the quantum analysis is finished Parameters: ------------------- epr : Object of QuantumAnalysis class swp_variable : the variable swept in data according to w...
8dfa860f73c5453ee970f204d4e03d6cef93d010
2,072
def getSpectra(dataframe, indices): """ Returns the files for training and testing Inputs ----------- dataframe: pd.DataFrame object from which we need to get spectra indices: row values for which we need the spectra Returns ----------- spec_vals: pd.DataFrame object ...
606757ffdde39c0847dd0402342441931d66a081
2,073
def config2(): """Configure for one of the restart tests.""" return Config.load(f""" id: cbc_binary_toolkit version: 0.0.1 database: _provider: tests.component.persistor_fixtures.mock_persistor.MockPersistorFactory engine: _provider: tests.component.engine_fixtures.mock_engine.MockLo...
ded0b43392e7e0308cca0f773d2ed687fd0818de
2,074
def diff_cases(couch_cases, log_cases=False): """Diff cases and return diff data :param couch_cases: dict `{<case_id>: <case_json>, ...}` :returns: `DiffData` """ assert isinstance(couch_cases, dict), repr(couch_cases)[:100] assert "_diff_state" in globals() data = DiffData() dd_count =...
545b35b7e37174f93df9e566bc0e1cd777948563
2,076
def rk4(a, b, x0, y0, nu=0, F=0, xdot = x_dot, ydot = y_dot): """rk(a, b, x0, y0, nu=0, F=0, xdot = x_dot, ydot = y_dot) Args: a (float) : Lower bound, t = a*2*pi b (float) : Upper bound, t = b*2*pi x0 (float) : Initial position of ball y0 (float) : Initial velocity of bal...
acd97edb74bc27d03908962e52431bc3fdb7a571
2,077
from furious.async import Async def decode_callbacks(encoded_callbacks): """Decode the callbacks to an executable form.""" callbacks = {} for event, callback in encoded_callbacks.iteritems(): if isinstance(callback, dict): async_type = Async if '_type' in callback: ...
0ff066a21bb2f0c0e0979898d218add1e46da544
2,078
def create_conv_block( use_depthwise, kernel_size, padding, stride, layer_name, conv_hyperparams, is_training, freeze_batchnorm, depth): """Create Keras layers for depthwise & non-depthwise convolutions. Args: use_depthwise: Whether to use depthwise separable conv instead of regular conv. ker...
08c45a1ca62ff290d5e34e1cb544618dababaad1
2,079
def select_eps_for_division(dtype): """Selects default values for epsilon to make divisions safe based on dtype. This function returns an epsilon slightly greater than the smallest positive floating number that is representable for the given dtype. This is mainly used to prevent division by zero, which produces...
7204b2b694c6df98af4608562616655b3c198178
2,080
def bpm_to_mspt(bpm, res=480): """ Coverts an integer value of beats per minute to miliseconds per quarter note """ return 60000 / res / bpm
6b962b8253eac29f52c48ca89a6dce0417adb11b
2,082
import numpy as np def pseudorandom(n, p, key): """ Pseudorandom array of integer indexes >>> pseudorandom(5, [0.5, 0.5], key=123) array([1, 0, 0, 1, 1], dtype=int8) >>> pseudorandom(10, [0.5, 0.2, 0.2, 0.1], key=5) array([0, 2, 0, 3, 0, 1, 2, 1, 0, 0], dtype=int8) """ p = list(p) cp...
5ec3dc8e66451a00d1f13f1df1df680879a16bc6
2,084
def next_hidden(s, A): """From a given state s, use the transition matrix A to generate the next hidden state. """ return choose_idx(A[s])
cc0b106ebeaa98ac2aeba947bd9ed0f653d233b5
2,085
import torch def create_network_rcnn(cls, opt): """Separate function for rcnn, which always loads weights first, no init.""" net = cls(opt) net.print_network() util.load_network_path(net, opt.fastercnn_loc, strict=True, rcnn_load=True) if len(opt.gpu_ids) > 0: assert(torch.cuda.is_availabl...
d653aa9435435ace4f10b134d28ee474353805bb
2,086
import tkinter def get_board_frame(window, mqtt_sender): """Builds the chessboard GUI.""" frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge") frame.grid() frame_label = ttk.Label(frame, text="Board") get_state = ttk.Button(frame, text="Get state") get_state["command"] = lambda...
d6f5a13312989613f8b945c8e73cedb9ee7e3851
2,087
import html def body(): """Get map page body. Returns: html.Div: dash layout """ graph_map = get_graph_map() if graph_map is None: return html.Div( dbc.Alert("Cannot retrieve data! Try again later!", color="danger") ) # Put everything in a dcc container an...
6474602d65f71dadce26e043c62f35ec0c489a0f
2,089
from datetime import datetime def custom_strftime(formatting: str, date: datetime.datetime) -> str: """Custom strftime formatting function, using fancy number suffixes (1st, 2nd, 3rd...)""" return date.strftime(formatting).replace("{S}", str(date.day) + suffix(date.day))
3199f6e0590f4bb01c1792976c75c7a0d4208831
2,090
def setup_twitter(config_file='config.py'): """Setup auth keys and session with Twitter client.""" config = {} execfile(config_file, config) twitter_obj = Twitter(auth=OAuth(config["access_key"], config["access_secret"], config["consumer...
bb811f3b6cabbe5dbf8f77d8e5217078f9a57c22
2,092
from datetime import datetime def create_datediff_test_nulls_df(): """Create DataFrame with nulls only for DateDifferenceTransformer tests.""" df = pd.DataFrame( { "a": [ datetime.datetime(1993, 9, 27, 11, 58, 58), np.NaN, ], "b": [ ...
542fd3fdf6fcd93a208e3f1f9cd2a76a0c34e46b
2,093
def business_days_list(start_date: date, end_date: date) -> list[date]: """ business days """ us_holidays = holidays.UnitedStates() days: list[date] = [] for the_date in get_list_of_days(start_date, end_date): if (the_date.weekday() < 5) and (the_date not in us_holidays): days.app...
daa36fe5fda5fc0857c1b29c75d7e784cafefe93
2,094
def test_3d(): """Test FE in 3D""" def setone(arr): arr[0, :, (arr.shape[0] - 1) // 2] = 1.0 return arr assert pipe( 5, lambda x: np.zeros((1, x, x, x), dtype=int), setone, solve_fe(elastic_modulus=(1.0, 10.0), poissons_ratio=(0.0, 0.0)), lambda x: n...
32f3d5fc18a31f01b2e366a3540ec77dd0e6080f
2,095
from typing import List def get_xray_edges(elements: List[str], wmin: float, wmax: float): """ Using xraydb, return the absorbtion edges Parameters ---------- elements: List[str] A list of the element symbols from which to query absorption edges. wmin: float The smallest wavel...
b78c0b999f4faf9e749b3b8388f0a581a5bff476
2,096
import urllib import json def get_mobility_link(): """Get Apple Mobility data link """ # get link with urllib.request.urlopen(index_url) as url: json_link = json.loads(url.read().decode()) base_path = json_link['basePath'] csv_path = json_link['regions']['en-us']['csvPath'] ...
a097e9c0b787a522283d31a8a13d4d13b824b77b
2,097
from datetime import datetime def active_shift(app, token, gqlClient): """returns the currently active shift if it exists""" with app.test_request_context(): request.headers = {'authorization': token} query = '''mutation CreateShift($Active: Boolean!, $StartTime: String) { createShift(...
345ba7f30421e28b879bc5b14409c437b9038d89
2,098
def get_batch_size(input): """ Infer the mini-batch size according to `input`. Args: input (tf.Tensor): The input placeholder. Returns: int or tf.Tensor: The batch size. """ if input.get_shape() is None: batch_size = tf.shape(input)[0] else: batch_size = int...
66201a3a8223ad442f54ac9551060093ee828f9b
2,099
def _order_points(pts: np.ndarray) -> np.ndarray: """Extract top left. top right, bottom left, bottom right of region Args: pts (np.ndarray[Tuple]): The coordinate of points Returns: np.ndarray: The coordinate of points. """ x_sorted = pts[np.argsort(pts[:, 0]), :] left_most =...
46dfb8a8e042929b2475bda2b01b39e5d871e02d
2,100
import logging import math def to_image(obj): """ allgemeine funktion zum anschauen von allen objekttypen (work in progress) gibt image (numpy arry),description zurück description sagt, was alles gemacht wurde um bild darzustellen """ descr = "" if (tf.is_tensor(obj)): obj = obj.numpy() logger...
4ae3be9758a647bbe2d0d2fedc080992840ab124
2,101
import re def matchPP(a_string): """assumes a_string is a string returns re match object if it finds two consecutive words that start with P, else returns None""" pattern = "[P|p]\w+\s[P|p]\w+" result = re.search(pattern, a_string) return result
c46eb4e0380a54cc36db0dc8969d17d65a546bf3
2,103
def setBoth(s1, s2): """ Sets both servo motors to specified number of degrees Args: s1, s2 (number): degrees for left and right servos respectively must be between -90 and 90 and will be rounded Raises: Exception if s1 or s2 is not a number Returns: None...
16385e9a8ad23011e9c10f66677afb703f6d19ed
2,104
import json def transfer_shfe_future_hq(date, file_path, columns_map): """ 将每天的数据统一标准 :return: pd.DataFrame 统一标准后的数据 """ ret = pd.DataFrame() data = json.loads(file_path.read_text()) hq_df = pd.DataFrame(data['o_curinstrument']) total_df = pd.DataFrame(data['o_curproduct']) bflag...
4e90164f96d4c5018774c0ad8d4deda7fa6dbeec
2,105
def comp_material_bsdf(arg_material_one:bpy.types.Material, arg_material_two:bpy.types.Material) -> bool: """指定マテリアルのBSDFノードを比較する 受け渡したマテリアルの出力ノードに接続されたプリシプルBSDFノードを比較する 比較対象の入力端子のデフォルト値が有効、かつ、全て同一の場合、Trueを返す Args: arg_material_one (bpy.types.Material): 比較マテリアル1 arg_material_two (bpy....
884c38c93ea4fd0c6907da0d2e5025a0980bed50
2,106
def run_filters(): """Runs filters ('PAINS', 'ZINC', 'BRENK', 'NIH')for molecule selected. Saves the information to the global molecule_info dict and returns the information as its own dict. Pass R Group IDs as queries: /filters?r1=A01&r2=B01 :returns: A json dictionary of the molecule, indexed ...
e1bc4719d412a73a7860f49978d47c459dc34d70
2,107
def read_template(engine, template_name): """Read template string from file and get path.""" template_file = get_template_file(engine, template_name) template_string = template_file.read_text() return template_string, template_file.parent
3dc55309df1575d2af2e4794e03e2ba4ccd166a2
2,108
def get_qbert_v3_url(qbert_url, project_id): """Keystone only hands out a v1 url I need v3.""" qbert_v3_url = "{0}/v3/{1}".format(qbert_url[0:-3], project_id) return qbert_v3_url
423e1f7a601f4ecafbc7d52d1f95fd59195f193e
2,109
def gen_all_holds(hand): """ Generate all possible choices of dice from hand to hold. hand: sorted full yahtzee hand Returns a set of tuples, where each tuple is sorted dice to hold """ # start off with the original hand in set set_holds = set([(hand)]) # now iterate with all...
5c8af5040f619fabef56918d399b5a1cab8893a4
2,110
def sndrcv(*args, **kwargs): # type: (*Any, **Any) -> Tuple[SndRcvList, PacketList] """Scapy raw function to send a packet and receive its answer. WARNING: This is an internal function. Using sr/srp/sr1/srp is more appropriate in many cases. """ sndrcver = SndRcvHandler(*args, **kwargs) retu...
6918dbf09bef672b95bab83126e6e4c0ec99e3bf
2,111
from typing import Optional def get_by_name(db_session: Session, *, name: str) -> Optional[Action]: """Return action object based on action name. Arguments: db_session {Session} -- SQLAlchemy Session object name {str} -- action name Returns: Optional[Action] -- Returns a Action o...
fb8c758d401fe09a36b3d2687a0e8e886edac594
2,112
def langstring(value: str, language: str = "x-none") -> dict: """Langstring.""" return { "langstring": { "lang": language, "#text": value, } }
dca23a329cfc87d8cfa52cd2b009ce723b7d2270
2,113
def chinese_half2full(): """Convert all halfwidth Chinese characters to fullwidth . Returns: """ def string_op(input_str:str): rstring = "" for uchar in input_str: u_code = ord(uchar) if u_code == 32: u_code = 12288 elif 33 <= u_code ...
e89a6314a57192e62b32e1f7e044a09700b5bb73
2,114
def euclidean_distance(p1, p2): """ Returns the Euclidean Distance of a particular point from rest of the points in dataset. """ distance = 0 for i in range(len(p1)-1): distance += (p1[i]-p2[i])**(2) return sqrt(distance)
dd06e44659fdd06972bd6a660afeb313de81c6fe
2,115
def img_histogram(file): """ Returns an image's histogram in a combined RGB channel and each individual channel as an array of 256 values. A 0 means that a tonal value is the max and 255 means there are 0 pixels at that value. """ with Image.open(file) as img: histogram = img.histogram()...
1f210316e752328190978f908143dd40c9ef6ba4
2,117
def absModuleToDist(magApp, magAbs): """ Convert apparent and absolute magnitude into distance. Parameters ---------- magApp : float Apparent magnitude of object. magAbs : float Absolute magnitude of object. Returns ------- Distance : float The distance resu...
a7d98ff479114f08e47afefc97a1119f5e8ff174
2,118
import base64 def decoded_anycli(**kwargs): """ Return the decoded return from AnyCLI request - Do not print anything :param kwargs: keyword value: value to display :return: return the result of AnyCLI in UTF-8 :Example: result = cli(url=base_url, auth=s, command="show vlan") deco...
223c4f9aabfef530896729205071e7fb8f9c8301
2,119
import pandas def open_mcrae_nature_cohort(): """ get proband details for McRae et al., Nature 2017 McRae et al Nature 2017 542:433-438 doi: 10.1038/nature21062 Supplementary table S1. """ data = pandas.read_excel(url, sheet_name='Supplementary Table 1') data['Individual ID'] += '|DDD...
8485fdc09c92bab20fc380a14f549f028be950b7
2,121
def copia_coords_alineadas(align1,align2,coords_molde,PDBname): """ Devuelve: 1) una lista con las coordenadas de coords_molde que se pueden copiar segun el alineamiento align1,align2. 2) una estimacion del RMSD segun la curva RMSD(A) = 0.40 e^{l.87(1-ID)} de Chothia & Lesk (1986) """ aanames = { "A":"ALA",...
48c730b43dd7059b6a6d7a068d884ecd27d3820e
2,122
def get_amati_relationship(value='o'): """ Return the Amati relationship and it's 1 sigma dispersion as given by Tsutsui et al. (2009). :param value: a string that can be 'o', '+', or '-'. The default is set to 'o' for the actual Amati relationship. '+' gives the upper bound of uncertainty and '-' gives the lower...
f7618f812dca45640376177383af2443085b6246
2,123
def load(name, final=False, torch=False, prune_dist=None): """ Returns the requested dataset. :param name: One of the available datasets :param final: Loads the test/train split instead of the validation train split. In this case the training data consists of both training and validation. :retu...
38f379076ba6f5562ab818113b319276f84bd081
2,124
def is_paragraph_debian_packaging(paragraph): """ Return True if the `paragraph` is a CopyrightFilesParagraph that applies only to the Debian packaging """ return isinstance( paragraph, CopyrightFilesParagraph ) and paragraph.files.values == ['debian/*']
726cd3d8c7cdfd14a55dc8bc9764cc9d037b1b63
2,125
def update_b(b, action_prob, yr_val, predict_mode): """Update new shape parameters b using the regression and classification output. Args: b: current shape parameters values. [num_examples, num_shape_params]. action_prob: classification output. [num_actions]=[num_examples, 2*num_shape_params] ...
ba8535d538ae0e0ac44c452f2fbe94a686b8e5a1
2,126
def setup(args): """ Create configs and perform basic setups. """ cfg = get_cfg() add_config(args, cfg) cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) cfg.merge_from_list(['MODEL.BUA.EXTRACT_FEATS',True]) cfg.merge_from_list(switch_extract_mode(args.extract_mode...
9dd4495a13c64d4832b889abdf94ffd01133c92a
2,127
def _earth_distance(time='now'): """ Return the distance between the Sun and the Earth at a specified time. Parameters ---------- time : {parse_time_types} Time to use in a parse_time-compatible format Returns ------- out : `~astropy.coordinates.Distance` The Sun-Earth ...
c8646b7e2aa9b821a9740235d5cc263623bd0ec0
2,128
async def DELETE_Link(request): """HTTP method to delete a link""" log.request(request) app = request.app group_id = request.match_info.get('id') if not group_id: msg = "Missing group id" log.warn(msg) raise HTTPBadRequest(reason=msg) if not isValidUuid(group_id, obj_cla...
193d6cb86a820a7492c768aad0a0e22fac76198f
2,129
def format_image(image): """ Function to format frame """ if len(image.shape) > 2 and image.shape[2] == 3: # determine whether the image is color image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) else: # Image read from buffer image = cv2.imdecode(image, cv2.CV_LOAD_IMA...
1649814cddab0037f89936d1a39af44d8d5203d9
2,130
def cpu_stats(): """Return various CPU stats as a named tuple.""" ctx_switches, interrupts, syscalls, traps = cext.cpu_stats() soft_interrupts = 0 return _common.scpustats(ctx_switches, interrupts, soft_interrupts, syscalls)
afdc9e95ba5d0b7760a1bbdf505b85f3fb0a0b7d
2,131
def has_reacted(comment, user, reaction): """ Returns whether a user has reacted with a particular reaction on a comment or not. """ if user.is_authenticated: reaction_type = getattr(ReactionInstance.ReactionType, reaction.upper(), None) if not reaction_type: raise template.T...
8cf537b204ae13c844e80a14b29f11e36d69097b
2,133
import requests def structure_query(compound, label='pyclassyfire'): """Submit a compound information to the ClassyFire service for evaluation and receive a id which can be used to used to collect results :param compound: The compound structures as line delimited inchikey or smiles. Optionally a...
cd7c0558dd61f493187169cea3562c96f63634d2
2,134
def create(*, db_session, ticket_in: TicketCreate) -> Ticket: """Creates a new ticket.""" ticket = Ticket(**ticket_in.dict()) db_session.add(ticket) db_session.commit() return ticket
644bcccc56c8fd97ec3c888f6e38c1fc2afc3585
2,136
def blur(img): """ :param img: SimpleImage, an original image. :return: img: SimpleImage, image with blurred effect. """ blank_img = SimpleImage.blank(img.width, img.height) for y in range(img.height): for x in range(img.width): blurred = blank_img.get_pixel(x, y) ...
9a7ac5085aea610a26a626e1d53bd243de19ad9e
2,137
def trans_pressure(src, dest="bar"): """ >>> """ return trans_basic_unit(src, dest, "pressure")
120888c024e6158a6e26ab699f7f4b5583cbf243
2,138
def test_accelerated_bypass_method_against_old(c_ctrl_rr): """Confirm that my changes to the bypass method maintain the same result as the old method""" OLD_HTCONSTS = dassh.region_rodded.calculate_ht_constants(c_ctrl_rr) def _calc_coolant_byp_temp_old(self, dz): """Calculate the coolant temper...
db6660b8ddc2f7ea409f7b334e4e161fceb743b2
2,140
import logging def vraec18(pretrained=False, **kwargs): """Constructs a _ResAE-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = _VRAEC(_VariationalBasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: try: model.load_state_di...
6b5e5a5d812b20c30bac3f81289a553bdc4884d4
2,142
import zlib def encode_zip(data): """Zip-compress data. Implies base64 encoding of zip data.""" zipped = zlib.compress(data) return encode_b64(zipped)
aa048125edd67a411715bf748bf832a6e6d7104f
2,143
def create_class_mask(img, color_map, is_normalized_img=True, is_normalized_map=False, show_masks=False): """ Function to create C matrices from the segmented image, where each of the C matrices is for one class with all ones at the pixel positions where that class is present img = The segmented image ...
97452e568d0a29b438a61fc96d90231a318e919b
2,144
import itertools def reconstruct_grid(mask, ds_dl): """ Reconstruction of 2d grid. Args: mask (ndarray): land mask used. ds_dl (ndarray): trained model prediction. """ landmask = np.argwhere(np.isnan(mask)) empty = np.zeros((ds_dl.shape[0], mask.shape[0], mask....
4d220e0d4ae96ee1ddc55e53f21f2a35d920b03e
2,145
def conv_kernel_initializer(shape, dtype=None): """卷积核初始化 和 tf.variance_scaling_initializer最大不同之处就是在于,tf.variance_scaling_initializer 使用的是 truncated norm, 但是却具有未校正的标准偏差,而这里使用正态分布。类似地,tf.initializers.variance_scaling使用带有校正后的标准偏差。 Args: shape: 卷积核的shape dtype: 卷积核的dtype Returns: 经过初始...
f7fd5665aeb8eb592a5f1f0f1785dfd84c9d8d98
2,146
def prediction_func(data, g_data, grid_search, param_list): """Function for using dataset to train a model and predicting prices for a generated data. Parameter search is done using RandomizedSearchCV since it is computationally more efficientcompared to GridSearchCV. In param_list, learning_rate,...
b747578879054947e91e5285b82cf3e07fa313da
2,147
def thv_to_zxy(theta, h): """Convert coordinates from (theta, h, v) to (z, x, y) space.""" cos_p = np.cos(theta) sin_p = np.sin(theta) srcx = +RADIUS * cos_p - h * sin_p srcy = +RADIUS * sin_p + h * cos_p detx = -RADIUS * cos_p - h * sin_p dety = -RADIUS * sin_p + h * cos_p return srcx, ...
64370dc6c4060a718506a243414afdd698881147
2,148
from datetime import datetime def get_most_stale_file(logpath=DEFAULT_PATH): """ returns the filename of the file in the fileset that was least recently backed up and the time of the last backup """ oldest_name = "" oldest_date = datetime.max for fstat in get_fileset_statlist(): la...
e0000847513ffeb97b8df0c26941ca4e3380f09d
2,149
from typing import Mapping from typing import Dict import re import logging def get_instances(context: models.Context) -> Mapping[str, Instance]: """Get a list of Instance matching the given context, indexed by instance id.""" instances: Dict[str, Instance] = {} if not apis.is_enabled(context.project_id, 'comp...
10f4eae30b0a5c752c45378574ba4620bd859320
2,150
def svn_fs_delete_fs(*args): """svn_fs_delete_fs(char const * path, apr_pool_t pool) -> svn_error_t""" return _fs.svn_fs_delete_fs(*args)
6e1f34d82899fc257c723990c55853b35f0b06d3
2,152
from re import T def translate_output(_output, n_classes, is_binary_classification=False): """ Gets matrix with one hot encoding where the 1 represent index of class. Parameters ---------- _output : theano.tensor.matrix Output sample. n_classes : int Number of classes (or size of...
03137e6b0704477a69211d454ee5e05a5ab02636
2,153
def _sphere_point_to_uv(point: Point) -> Vec2d: """Convert a 3D point on the surface of the unit sphere into a (u, v) 2D point""" u = atan2(point.y, point.x) / (2.0 * pi) return Vec2d( u=u if u >= 0.0 else u + 1.0, v=acos(point.z) / pi, )
c0eb4abb1ebc55f74b908a85f0cb94f71a528c32
2,155
import tqdm def generate_formula_dict(materials_store, query=None): """ Function that generates a nested dictionary of structures keyed first by formula and then by task_id using mongo aggregation pipelines Args: materials_store (Store): store of materials Returns: Nested dic...
ae232c806972262029966307e489df0b12d646f5
2,156
def truncate(wirevector_or_integer, bitwidth): """ Returns a wirevector or integer truncated to the specified bitwidth :param wirevector_or_integer: Either a wirevector or and integer to be truncated :param bitwidth: The length to which the first argument should be truncated. :return: Returns a tuncate...
7ff6d22061944f4202bc69dfde109c1cead20972
2,158
def pcoef(xte, yte, rle, x_cre, y_cre, d2ydx2_cre, th_cre, surface): # Docstrings """evaluate the PARSEC coefficients""" # Initialize coefficients coef = np.zeros(6) # 1st coefficient depends on surface (pressure or suction) if surface.startswith('p'): coef[0] = -sqrt(2*rle) e...
43cc56ec7f29267678ebbc3572633e5073cda117
2,159
def iscircular(linked_list): """ Determine whether the Linked List is circular or not Args: linked_list(obj): Linked List to be checked Returns: bool: Return True if the linked list is circular, return False otherwise """ slow_runner = linked_list.head fast_runner = linked_lis...
04f86497dae2a2ee77afd37f13bdba8e18ae52b9
2,162
def shape_extent_to_header(shape, extent, nan_value=-9999): """ Create a header dict with shape and extent of an array """ ncols = shape[1] nrows = shape[0] xllcorner = extent[0] yllcorner = extent[2] cellsize_x = (extent[1]-extent[0])/ncols cellsize_y = (extent[3]-extent[2])/nrows i...
957b59e7f464901a5430fd20ab52f28507b55887
2,163
def build_encoder(opt, embeddings): """ Various encoder dispatcher function. Args: opt: the option in current environment. embeddings (Embeddings): vocab embeddings for this encoder. """ if opt.encoder_type == "transformer": return TransformerEncoder(opt.enc_layers, opt.rnn_...
73b379545aeeb3226ea019cad0a692b00cd7630b
2,164
def efficientnet_b3b(in_size=(300, 300), **kwargs): """ EfficientNet-B3-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (300, 300) ...
1d7e0bffe67f9d2f340563b21e1f995201877165
2,166
import logging def logged(class_): """Class-level decorator to insert logging. This assures that a class has a ``.log`` member. :: @logged class Something: def __init__(self, args): self.log(f"init with {args}") """ class_.log= logging.get...
cd58e355151ab99aa1694cbd9fb6b710970dfa19
2,167
def TableInFirstNSStart(builder): """This method is deprecated. Please switch to Start.""" return Start(builder)
5ea3cf66842eaf026a36bb241c277076cc8650b8
2,168
def dicom_to_nifti(dicom_input, output_file=None): """ This is the main dicom to nifti conversion function for ge images. As input ge images are required. It will then determine the type of images and do the correct conversion :param output_file: filepath to the output nifti :param dicom_input: dir...
0b77d190c2379e9b2ad5fbf9217e1604a7df8bc9
2,169
def lot_vectors_dense_internal( sample_vectors, sample_distributions, reference_vectors, reference_distribution, metric=cosine, max_distribution_size=256, chunk_size=256, spherical_vectors=True, ): """Efficiently compute linear optimal transport vectors for a block of data provid...
d7f9eaad6b7292f2c28621f361094a88e7deb8a6
2,170
import rasterio as rio def load( filename, rsc_file=None, rows=None, cols=None, band=1, **kwargs, ): """Load a file, either using numpy or rasterio""" if rsc_file: rsc_data = load_rsc(rsc_file) return load_stacked_img(filename, rsc_data=rsc_data, rows=rows, cols=cols) ...
873933b80b7e87f64b10ad74cc8ed25238a93fb3
2,171
def simple_scan_network(): """ Do a simple network scan, which only works if your network configuration is 192.168.1.x """ base_ip = "192.168.1." addresses = ['127.0.0.1'] for index in range(1, 255): addresses.extend([base_ip + str(index)]) return addresses
b0f19ae1c98678e87d270b308b5359df9a6a4d30
2,172
def channel_lvlv_2jet(): """ Mostly based on table 8 of the combination paper for the uncertainties and table 9 for the event counts. """ channel = ROOT.RooStats.HistFactory.Channel( "HWWlvlv2Jet" ) container.append(channel) channel.SetData(55) background = ROOT.RooStats.HistFactory.Sample("background") backgr...
f60609a0bf6f22dc850fcb52c4a19b6bae737abc
2,174
def vtkVariantStrictEquality(s1, s2): """ Check two variants for strict equality of type and value. """ s1 = vtk.vtkVariant(s1) s2 = vtk.vtkVariant(s2) t1 = s1.GetType() t2 = s2.GetType() # check based on type if t1 != t2: return False v1 = s1.IsValid() v2 = s2.IsV...
cb529c35f6dfc7e20fcff79d5c38b41bd43f1292
2,175
def is_network_failure(error): """Returns True when error is a network failure.""" return ((isinstance(error, RETRY_URLLIB_EXCEPTIONS) and error.code in RETRY_HTTP_CODES) or isinstance(error, RETRY_HTTPLIB_EXCEPTIONS) or isinstance(error, RETRY_SOCKET_EXCEPTIONS) or ...
647d10b257b1cb7f78243629edd2b425104f1787
2,176
import torch def predict(model, X, threshold=0.5): """Generate NumPy output predictions on a dataset using a given model. Args: model (torch model): A Pytroch model X (dataloader): A dataframe-based gene dataset to predict on """ X_tensor, _ = convert_dataframe_to_tensor(X, []) ...
57b6137cc8f7e0753e6438432f56b471717a5d88
2,177
def color_image( img: np.ndarray, unique_colors=True, threshold=100, approximation_accuracy=150 ) -> np.ndarray: """ This function detects simple shapes in the image and colors them. Detected figures will be also subscribed in the final image. The function can detect triangles, quadrilateral, and c...
5637febc69dcc2b3e641f0d79f2e21c6dc7d04ec
2,178
from pathlib import Path def restore_model(pb_path): """Restore the latest model from the given path.""" subdirs = [x for x in Path(pb_path).iterdir() if x.is_dir() and 'temp' not in str(x)] latest_model = str(sorted(subdirs)[-1]) predict_fn = predictor.from_saved_model(latest_model) return pr...
bded95b196081e19ca1c70127871abb99d3526d0
2,179
import math def _generate_resolution_shells(low, high): """Generate 9 evenly spaced in reciprocal space resolution shells from low to high resolution, e.g. in 1/d^2.""" dmin = (1.0 / high) * (1.0 / high) dmax = (1.0 / low) * (1.0 / low) diff = (dmin - dmax) / 8.0 shells = [1.0 / math.sqrt(dm...
52fa4309f2f34a39a07d8524dd7f226e3d1bae6a
2,180
from typing import Optional from typing import Tuple def add_ports_from_markers_square( component: Component, pin_layer: Layer = (69, 0), port_layer: Optional[Layer] = None, orientation: Optional[int] = 90, min_pin_area_um2: float = 0, max_pin_area_um2: float = 150 * 150, pin_extra_width: ...
68858a17b5187e064232f0c101ddf9c4e812c233
2,181
def P(Document, *fields, **kw): """Generate a MongoDB projection dictionary using the Django ORM style.""" __always__ = kw.pop('__always__', set()) projected = set() omitted = set() for field in fields: if field[0] in ('-', '!'): omitted.add(field[1:]) elif field[0] == '+': projected.add(field[1:]) ...
d88a428f5eae1e57bd3b5ddf0d31e6e7c122c27d
2,182
def get_page_url(skin_name, page_mappings, page_id): """ Returns the page_url for the given page_id and skin_name """ fallback = '/' if page_id is not None: return page_mappings[page_id].get('path', '/') return fallback
6ead4824833f1a7a002f54f83606542645f53dd6
2,183
def create_form(erroneous_form=None): """Show a form to create a guest server.""" party_id = _get_current_party_id_or_404() setting = guest_server_service.get_setting_for_party(party_id) form = erroneous_form if erroneous_form else CreateForm() return { 'form': form, 'domain': set...
2d8e9cd6597e4ccb1b9f39d77cca45b354d99371
2,185
def apply(task, args, kwargs, **options): """Apply the task locally. This will block until the task completes, and returns a :class:`celery.result.EagerResult` instance. """ args = args or [] kwargs = kwargs or {} task_id = options.get("task_id", gen_unique_id()) retries = options.get(...
600bc142ca8d96bd020db5cb82103169d255d970
2,186
from typing import Optional from typing import Callable def exp_post_expansion_function(expansion: Expansion) -> Optional[Callable]: """Return the specified post-expansion function, or None if unspecified""" return exp_opt(expansion, 'post')
6d49f5e40b7c900470a5c84b37d9da1666b217c2
2,187
def return_(x): """Implement `return_`.""" return x
6557a37db2020bdbb0f9dcf587f2bd42509ff937
2,188
def create(platformDetails): """ This function creates a new platform in the platform list based on the passed in platform data :param platform: platform to create in platform structure :return: 201 on success, 406 on platform exists """ # Remove id as it's created automatically ...
a6b27d6b530ccc11134a001ac3b49c6cb89475a3
2,190