content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def make_table(excel_file, excel_sheet, define_module, sheet_name): """从Sheet取出table来""" table = {} col_list = [] col_defines = {} key_name = define_module.config['key'] for row, row_values in enumerate(excel_sheet.rows): if row == 0: # 第1列为字段 for col_name in row_values: col_list.append(col_name) col...
e8ff77c4b53600208c800aa6ce1d35405e2054bb
68,534
def load_two_sp_sod_data(fle): """ Given filename `fle` corresponding to Sod shocktube spacetime data, return: space: 1D spatial coordinates of shocktube time: 1D temporal coordinates of shocktube sc_1 -> sc_2 : two spacecraft trajectories (x,t) through spacetime st_data: raw plasma var...
866b11ef7214856ae0ffd6e2496cd0cb81b5ffb5
68,535
import torch def ry(phi): """Single-qubit rotation for operator sigmay with angle phi. ------- result : torch.tensor for operator describing the rotation. """ return torch.cat((torch.cos(phi / 2).unsqueeze(dim=0), -1 * torch.sin(phi / 2).unsqueeze(dim=0), torch.sin(phi / 2).u...
c1ec83ecf85132f7522770db646b7e0e54a52279
68,536
def minmatch_factor_validator( count_df: DataFrame, column_index: int, min_match: float = 10, factor: float = 2 ) -> bool: """Validates min_match and factor for adapter/organism to be considered as resulting adapter/organism. Args: count_df: adapter: Adapters sequence co...
8d422dfafdd202a608713343a37689417c4d660b
68,537
from typing import Concatenate def CMTL(input_shape=None, num_classes=10): """ 定义模型 :param input_shape: :param num_classes: :return: """ inputs = Input(shape=input_shape) # shared layer shared = Conv2D(16, (9, 9), padding='same')(inputs) shared = PReLU(shared_axes=[1, 2])(shar...
4e26f7a2a32ba7c9de9406d692503d957be2b605
68,538
import numpy import torch def image_to_text(captions, images, npts=None, verbose=False): """ Images->Text (Image Annotation) Images: (5N, K) matrix of images Captions: (5N, K) matrix of captions """ if npts == None: npts = images.size()[0] / 5 npts = int(npts) ranks = nump...
88e10f7507f3d1e8cc0fc3860c582d1a2af0abde
68,539
def saveper(): """ Real Name: b'SAVEPER' Original Eqn: b'TIME STEP' Units: b'Month' Limits: (0.0, None) Type: component b'The frequency with which output is stored.' """ return time_step()
2be0ebe821720ef01e91987caddeebacb076dea1
68,540
def snr_ecc_evolving(m_1, m_2, f_orb_i, dist, ecc, harmonics_required, t_obs, n_step, position=None, polarisation=None, inclination=None, t_merge=None, interpolated_g=None, interpolated_sc=None, n_proc=1, ret_max_snr_harmonic=False, ret_snr2_by_harmonic=Fal...
84b1ba3a748bf24f18b97e1f5e11272f4613ce24
68,541
def make_plural(word): """Makes word plural if it's a noun or verb. Returns None.""" # special if word == "I": return add_s(word) # elif is_foreign_origin(word): # return add_s(word) # fix this # elif is_irr_noun(word): return IRRNOUNS.get(word) # common elif final_es(...
a92046a5ff6f5fbc22a0e60124a91455c1582bc7
68,544
import time def execute_s3_tests(client_node, build): """ Execute the s3-tests Args: client_node: node to execute tests from Returns: 0 - Success 1 - Failure """ log.info("Executing s3-tests") try: base_cmd = "cd s3-tests; S3TEST_CONF=config.yaml ~/virtual...
71a11d5764b0ad02da284ff7f6b0f55e12136b60
68,545
from typing import List def read_odim(odim_file: str, lazy_load: bool = True, **kwargs) -> List: """ Read an ODIM H5 file. Parameters: =========== odim_file: str ODIM H5 filename. lazy_load: bool Lazily load the data if true, read and load in memory the entire dataset ...
ae3150d0b0eb13dc54a757c4169ae9be7cf5d50a
68,546
import getpass def getSystemUserName(): """Finds out user inf (currently just the logged user name) for Windows and Posix machines. sets a USER_NAME variable containing the logged user name defines a UNKNOWN_USER variable to which username falls back. :return: (str) current user name """ try:...
71ca83d73358d2ef220071ecf52af8a3975db17f
68,549
def get_backbone(l_sites, r_sites, rootsMask=None, N=None, include_tails=True): """Find the positions between the root loops aka the backbone. """ backboneidxs = [] if rootsMask is None: rootsMask = get_roots(l_sites, r_sites) rootsSorted = np.where(rootsMask)[0][np.argsort(l_sites[rootsMas...
034075eaf00111d535446bdc79642eaa56da7b63
68,550
from typing import Optional def get_json_download(prefix: str) -> Optional[str]: """Get the download link for the latest OBOGraph JSON file.""" entry = get_resource(prefix) if entry is None: return None return get_external(prefix, "obofoundry").get("download.json")
ab973e0bcb850fea194324b5cd58e23026d79ff1
68,552
import math def most_probable_isotopic_composition(*args, **kwargs): """Calculate the most probable isotopic composition of a chemical formula or |Composition| object. For each element, only two most abundant isotopes are considered. Parameters ---------- formula : str, optional A st...
f649f86cc777c2e0c9bdb72c1cfecbe42a437058
68,553
def get_new_thread_name(extra_prefix=""): """ <Purpose> Returns a new and unique name that can be associated with a new thread. This is used so that threads can be uniquely identified. This call is thread safe, and guarentees unique-ness. <Arguments> extra_prefix: This is an optional...
69cb2024c2fa331b7e3a53e5399164ec50fba037
68,554
import numpy def partition(a, b, n): """ Utility routine to construct the non-uniform partition, t, for the interval [a,b] using (n+1) nodes. For convenience I just use the Chebyshev nodes of the second kind. Returns t as a column vector. """ return ((a+b)/2 - (b-a)/2*numpy.cos(numpy.linspac...
68d6e0093a6e7115ebeadfc5852132f531e2260e
68,555
import binascii def opcode_list(script): """Disassemble the given script. Returns a list of opcodes.""" opcodes = [] pc = 0 while pc < len(script): opcode, data, pc = get_opcode(script, pc) if len(data) > 0: opcodes.append(binascii.hexlify(data).decode("utf8")) ...
3a0cb9c8059fd1e95049dc68243f2f1a001be3e3
68,556
def make_subfolder(path, subfolder): """helper method that puts given file in given subfolder""" basename, dirname = path.name, path.parent path = dirname.joinpath(subfolder, basename) path.parent.mkdir(exist_ok=True, parents=True) return path
473f71f6ac74fe40eeb1b96c584a37f4d16d130b
68,557
def swap_diff(start, goal, limit): """A diff function for autocorrect that determines how many letters in START need to be substituted to create GOAL, then adds the difference in their lengths. """ # BEGIN PROBLEM 6 list_start = list(start) list_goal = list(goal) def count_changes(lst_st...
436ac431133e9b5e0aeb9d0df930e521eb329ee9
68,558
def xrf_peak(name=None, amplitude=1, sigma=0.1, center=None, shape='gaussian', sigma_params=None, **kws): """create an XRF Peak Parameters: ----------- name: name of peak -- may be used for auto-setting center 'Fe Ka1', 'Pb Lb1', etc amplitude: center: si...
67202dec44c2530e0a886f077cdc6309e664e7ad
68,559
def GetColumns(dBase, table, fieldString, user='sysdba', password='masterkey', join='', cn=None): """ gets a set of data from a table **Arguments** - dBase: database name - table: table name - fieldString: a string with the names of the fields to be extracted, this should be a comm...
c21d80d495a9fe5c65ffe6994a67630b3aa46153
68,560
def read_csv_labels(fname): """读取fname来给标签字典返回一个文件名""" with open(fname, 'r') as f: # 跳过文件头行(列名) lines = f.readlines()[1:] tokens = [l.rstrip().split(',') for l in lines] return dict(((name, label) for name, label in tokens))
bb5a6c9ddacb6566b3b5d44af5f55b09fb6691ea
68,562
def foodHeuristic(state, problem): """ Your heuristic for the FoodSearchProblem goes here. This heuristic must be consistent to ensure correctness. First, try to come up with an admissible heuristic; almost all admissible heuristics will be consistent as well. If using A* ever finds a solutio...
2f8c46700b983641a840b5975fa115343b48923a
68,563
def cw_cloed_form(time_span, n, delta_r0, delta_v0): """ Computes the closed form solution of the CW equations in the LVLH frame Arguments: time_span : time_span of the orbit n : mean motion delta_r0 : Initial conditions of position delta_r0 = [x,...
45d77d6cc056a2c6549ac7c958880db8d5238551
68,564
def emojify_hunger(level: int) -> str: """Create a hunger emoji track.""" filled = level unfilled = 5 - level hunger = [__hungermoji(True) for _ in range(filled)] unfilled = [__hungermoji(False) for _ in range(unfilled)] hunger.extend(unfilled) return " ".join(hunger)
4bc5ee055af8701ae7f857927d01d877aca662dc
68,565
def assemble_helmholtz_kernel( sources, targets, wavenumber, dtype=np.complex128, parallel=True ): """ Assemble the Helmholtz kernel matrix for many targets and sources. Returns the Helmholtz kernel matrix for the Green's function g(x, y) = exp(1j * k * | x- y| ) / (4 pi * | x - y |) Paramete...
35d8077866a69f631d053364611ad5a6f4ebe245
68,566
def exists(name): """Returns true if the evaluation exists""" if reseval.is_local(name): return False try: # Get config config = reseval.load.config_by_name(name) # Get credentials credentials = reseval.load.credentials_by_name(name, 'crowdsource') except File...
987aede5b62d59bed47db367e62a19d058b92689
68,567
def voxelPathList2matrix(voxelPathList): """ voxelPathList: ['~/Datasets/3d-r2n2-datasat/ShapeNetVox32/03001627/1a8bbf2994788e2743e99e0cae970928', ...] Returns: List_size x 1 x 32 x 32 x 32 (numpy array) """ size = len(voxelPathList) voxels = np.zeros((size,) + g.VOXEL_INPUT_SHAPE, dtype=np.floa...
d9abb9dceae0daa24a785b331735a3d1af1bce05
68,568
def test_twoAxesOffAxis(l, n): """Test for a system with two axes. Three values, two on-axis, one off-axis. >>> test_twoAxesOffAxis(0, 0) 0 >>> test_twoAxesOffAxis(1, 1) 50.0 >>> test_twoAxesOffAxis(2, 2) 200.0 >>> test_twoAxesOffAxis(1, 0) 100.0 >>> test_twoAxesOffAxis(0, 1) ...
79c065294063e6c0e70bcb54264e6cfb66e28a95
68,569
def fix_orientation(img, save_over=False): """ `img` can be an Image instance or a path to an image file. `save_over` indicates if the original image file should be replaced by the new image. * Note: `save_over` is only valid if `img` is a file path. """ path = None if not isinstance(img, Im...
65b24c6db2c09859e697caf61ce958071b324b28
68,570
import tempfile def get_logprop_file(logger, template, pattern, project): """ Return the filename of file with logging properties specific for given project. """ with open(template, 'r') as f: data = f.read() data = data.replace(pattern, project) with tempfile.NamedTemporaryFile...
061254a5e65a08c7e5ee8367c94abaee04238e61
68,572
def load_img(image_buffer): """ 画像ファイル(バイトデータ)をPILで読み込む :param image_buffer: 画像ファイルのバイトデータ :return: PIL.Imageオブジェクト """ return Image.open(BytesIO(image_buffer))
e3b2546f9a515726787e90265949e74622a13b7a
68,573
def get_driver_list(): """ Return the names of the registered object storage drivers :return: list of strings from driver names """ return object_store.ObjectStorageDriver.registry.keys()
c992e933c1d002518b604d41a7983e37f051691d
68,575
from typing import Dict def colour_style(use_style: Boolean = True) -> Dict: """ Returns *Colour* plotting style. Parameters ---------- use_style Whether to use the style and load it into *Matplotlib*. Returns ------- :class:`dict` *Colour* style. """ constan...
ba969f603c5724002a38102ed19676140b59b386
68,576
def quantize(image, nlevels): """Quantize an image into integers 0, 1, ..., nlevels - 1. image -- a numpy array of type float, range [0, 1] nlevels -- an integer """ tmp = np.array(image // (1.0 / nlevels), dtype="i1") return tmp.clip(0, nlevels - 1)
3746b6aa322561ccd02654a6b0c1b034e5cdce0f
68,577
def _parser_parse_expr_to_str(text): """Return parse tree from `tla.parser.parse_expr`.""" r = parser.parse_expr(text, nodes=to_str.Nodes) text = r.to_str(width=80) return r
f53c7d2cd2b48bb4d1ae114969aff9ce30a13b00
68,578
def Iyy_beam(b, h): """gets the Iyy for a solid beam""" return 1 / 12. * b * h ** 3
8912b769b1bf8f91d2bb7eefad261c0e4f9f4026
68,579
import ctypes def create_rects(rect_list): """ Create a vertex buffer for a set of rectangles. """ v2f = [] for shape in rect_list: v2f.extend([-shape.width / 2, -shape.height / 2, shape.width / 2, -shape.height / 2, shape.width / 2, shape.height / 2, ...
34de899d55523ddae3998ca87248608de3cfb7ce
68,580
def _get_grouped_pathways(end_nodes_dict): """ From end_nodes_dict, makes a list of grouped_pathway lists""" grouped_pathways = [] for end_nodes in end_nodes_dict: for reactions in end_nodes_dict[end_nodes]: for scores in end_nodes_dict[end_nodes][reactions]: grouped_path...
7d969fa8f18061847f3f71de0a02799e845fc55d
68,581
import posixpath def relpath(path, start): """Return a relative version of a path""" if not path: raise ValueError("no path specified") start_list = posixpath.abspath(start).split(posixpath.sep) path_list = posixpath.abspath(path).split(posixpath.sep) # Work out how much of the filepath i...
c2f5b054387a565a11a21643b96a8a82781475ff
68,582
def _get_client_ip(request) -> str: """ Get client ip address from request instance. We can fetch ip address from these classes. - django.core.handlers.wsgi.WSGIRequest - rest_framework.request.Request """ ip: str x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if ...
950169b8b1052057eec14e03e8d6fbc9d162662d
68,583
import re def tokenize(tweet): """Removes punctuation & excess whitespace, sets to lowercase, and stems tweets. Returns a list of stemmed tokens.""" tweet = " ".join(re.split("[^a-zA-Z]*", tweet.lower())).strip() # tokens = re.split("[^a-zA-Z]*", tweet.lower()) tokens = [stemmer.stem(t) for t in t...
f89578a80873c74e58c03811d91f51b5eb088c4e
68,584
from typing import Dict import json def generate_rewards_in_range( chain: str, start: int, end: int, save: bool, past_tree: Dict, tree_manager: TreeManager, boosts: Dict, ): """Generate chain rewards for a chain within two blocks :param chain: chain to generate rewards :param ...
c0a6627ee30ac1f34965d22c91444ad63eeb06b0
68,585
def is_up(element1, element2): """Is element2 on the up of element1. Args: element1: XML element1 dump from UI. element2: XML element2 dump from UI. Returns: Whether element2 is on the up of element1. """ [e1_x1, e1_y1, e1_x2, e1_y2] = get_element_bounds(element1) [e2_x1, e2_y1, e2_x2, e2_y2] ...
1c5d0b2c6171e63dff47e245e1eb6b2b7fcfe26e
68,586
from typing import Callable import torch from typing import Tuple def im_path_to_tensor(im: str, transform: Callable[[Image.Image], torch.Tensor]) -> Tuple[torch.Tensor, Tuple[float, float]]: """Converts an image into a network input. Parameters ---------- im : str a color image in BGR order ...
f6b8a476696bb55997997525634bcb4a7426a1bf
68,587
import logging def read_contours_text(boxed_image, contours, img): """store on the location where it is located in the image. here it will be top-left pixel location as the key""" logging.info('Reading the text inside the contour plotted') image_text_dict = get_text_with_location(boxed_image, contours, im...
dc4f426d823a1dc7e11e4db502048714cf632a5c
68,591
def convert_audio_segment(audio_segment): """ Create a GCS AudioSegment """ audio_segment \ .set_channels(1) \ .set_sample_width(2) \ .set_frame_rate(__sample_rate(audio_segment)) return audio_segment
ca100cee32fa715b039a79fa2d1018d0fb9c6052
68,592
def _Volume(kwargs): """成交量图""" df = kwargs.get('df') limit_start = kwargs.get('limit_start') limit_end = kwargs.get('limit_end') colors = kwargs.get('colors') data = df.loc[limit_start:limit_end, :] hovertext = _get_date_hovertext(data) trace = go.Bar( x=np.arange(data.shape[0])...
c7d3456fa2005df192e52793fa640f5331197fd7
68,595
def get_logging_format_string(package): """Get format string for all loggers Discovers all modules to determine the space needed to nicely format log messages from all modules. """ module_names = get_dot_separated_submodule_names(package) max_module_name_length = max(len(name) for name in modul...
7b81ffeec2767c8687cf1757dca5a4a31c4d0557
68,596
def multicast(self, subject=None, subject_selector=None, selector=None): """Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each subscription to the resulting sequence causes a separate multicast invocation, exposing ...
b9dd224e5a3fff883072f5dde058bdd37c20adfe
68,597
import tqdm import torch def compute_compression(model, data, context, batch_size, verbose=False, tbw=None, tok=None, skip=0): """ Compute the _compression_ of a dataset under a model. That is, given a model, in how many bits could we represent the dataset. This requires us to tu...
3db6da12eb00b4250bd4df34dff37e00a8e2d16a
68,598
def panel2array(panel): """convert the panel to datatensor (numpy array) without btc """ without_btc = np.transpose(panel.values, axes=(2, 0, 1)) return without_btc
4efc88dd11cde14fa291547f6bc4def95f3860d1
68,599
import urllib import ast def find_path(start, finish, security=5, invert=0): """ Returns a list of system objects which represent the path. start: system_id of first system finish: system_id of last system security: sec level of system * 10 invert: if true (1), use security as highest seclevel...
1fee78f6899cf6d4f28141214ec50b1b5de656dd
68,600
from typing import Union from typing import Callable from typing import Any from typing import Dict import time def debounce(duration: Union[float, int] = 0.1) -> Callable[..., Any]: """Ensure a function called with the same arguments executes only once per `duration` (default: 100ms). """ def decora...
11d8d52fec00a6eb0535ef4f6a544b7b349749cc
68,601
def set_student_i_d(person_id: str = None, student_id: str = None): """ Sets a student's ID :param person_id: The numeric ID of the person whose student ID you'd like to change. :param student_id: The new student ID :returns: String containing xml or an lxml element. """ return get_anonymo...
61b51ba20b2d9a5845e6441344c251f55467e175
68,602
def signalumap(jsonfiles, **kwargs): """ Performs UMAP on signal matrices read from the given files; returns the coordinates of the elements in the reduced dimension space. Each JSON file should contain a matrix with the same number of elements, corresponding to the matrix rows. The vectors from each fi...
12719ff8bfce59af39b2e900e640e785c37294cf
68,603
from datetime import datetime def pls(X,Y,A,*,mcsX=True,mcsY=True,md_algorithm='nipals',force_nipals=False,shush=False,cross_val=0,cross_val_X=False): """ Projection to Latent Structures routine by Salvador Garcia-Munoz (sgarciam@ic.ac.uk ,salvadorgarciamunoz@gmail.com) Inputs: X,Y...
23dadf785068d06d3d2488748ffb84bad8baa00e
68,604
def GetLastCollectionPathInfos(client_paths, max_timestamp=None): """Returns PathInfos corresponding to last collection times. Args: client_paths: An iterable of ClientPath objects. max_timestamp: When specified, onlys PathInfo with a timestamp lower or equal to max_timestamp will be returned. Ret...
80cb02e7c707145e008166f21da40ee8b3bc0cfd
68,605
from typing import Tuple from typing import Callable def create_acoustic_bottleneck_block( *, # Convolution configs. dim_in: int, dim_inner: int, dim_out: int, conv_a_kernel_size: Tuple[int] = (3, 1, 1), conv_a_stride: Tuple[int] = (2, 1, 1), conv_a_padding: Tuple[int] = (1, 0, 0), ...
8ae884a0d3d62550440354ec5608b98dc80609df
68,606
from re import T def gen_updates_adadelta(loss, all_parameters, learning_rate=1.0, rho=0.95, epsilon=1e-6): """ in the paper, no learning rate is considered (so learning_rate=1.0). Probably best to keep it at this value. epsilon is important for the very first update (so the numerator does not become 0). ...
be2ef23a612ee4792a83d35ae864ea5db3389428
68,607
def read_user_header(head): """ The 'User-Id' header contains the current online user's id, which is an integer -1 if no user online :param head: the request's header :return: online user's id, abort type error if the header is not an integer. """ try: return int(head['User-Id']) ...
95586f32b698283f33c9271b5ffdf61a934dbb4a
68,608
def acceptance_probability(alpha, multiplier): """The probability of a user accepting a ride given the multiplier""" return np.exp(-alpha * (multiplier - 1))
bfbeff9b6b8410babadc22ffa224fd02ca8a4aff
68,609
import re def get_info(printer_address): """ Returns an object with basic printer information such as name etc.""" info_result = send_gcode(printer_address, GCode.GET_INFO) printer_info = {} info_fields = ['Type', 'Name', 'Firmware', 'SN', 'X', 'Tool Count'] for field in info_fields: rege...
50a2873a4b5df4b0d43085da731b78cd54d61968
68,610
import time from datetime import datetime def t_dt_utc_a(): """Time, format datetime, scale utc, array entry""" return time.Time( [datetime(2015, 6, 30) + timedelta(hours=23, minutes=59, seconds=i) for i in range(0, 2)], scale="utc", fmt="datetime", )
ade94944b928e36ba1b075451f26909a5e7ebcf8
68,611
def message_max(message, max): """ Returns a given message with a maximum length. Primarily used for additional logging :param message: a message intended to send to twitter :param max: the maximum length of the message :returns: the message truncated to a maximum length """ if len(message)...
a4146ca18eb17d5f766a09f1ef1c425a71c1d2bd
68,612
def register_shellcontext(app): """Register shell context objects.""" def shell_context(): """Shell context objects.""" return { 'db': db, 'Person': person, 'Movie': movie, 'Actors': actors, 'Writers': writers, 'Directors': ...
1bc82e99d840ff499715122e9ed0095822c9d12f
68,613
from typing import List from typing import Any def fermion_opstring_to_bitstring(ops) -> List[List[Any]]: """Convert an openfermion FermionOperator object into the corresponding bitstring representation with the appropriate coefficient. Args: ops (FermionOperator): A product of FermionOperators w...
09894f4b9d91d6c473651b25e2523df6b1ffae15
68,614
from typing import Tuple def apply_burn(o1_factors: Tuple[Mass, Mobile], o2_factors: Tuple[Heat],) -> SetFactor[Mass]: """Reduces the mass of something conditioned it is on something with heat. :param o1_factors: First set of factors. :param o2_factors: Second set of factors. :return: Change of mass ...
ebf3ca873e78fc3b58b0ec36477c7e245189ae10
68,615
import uuid def GenerateUID(): """This will generate a unique ID which will be assigned""" return str(uuid.uuid1()).lower()
2b93b6db1de6139419dd13084147efe3e39de5ee
68,616
from typing import Iterable from re import T def all_meet_predicate(iterable: Iterable[T], predicate: Predicate[T]) -> bool: """ Version of all which checks values against a predicate. :param iterable: An iterable of values. :param predicate: A predicate which checks those values. :return: ...
48e0c1b2460313e371f4e843334de04d9aaee626
68,618
def markovKdV(u,M,alpha): """Computes nonlinear part of Markov term in KdV C_k(u,v) = -(alpha * 1i * k) / 2 * sum_{i+j = k} u_i v_j where the sum of i and j is over a "full" system with M positive modes (user specified) Computed in real space to avoid loops and then converted back to ...
27365d95bc03e888db5e060e8ee26ba24cc51450
68,619
def recursive_merge(a, b): """Recursively merge two dicts. Updates a.""" if not isinstance(b, dict): return b for k, v in b.items(): if k in a and isinstance(a[k], dict): a[k] = recursive_merge(a[k], v) else: a[k] = v return a
3d98b804e95acf12a147b298f2c2642b2b4f96cb
68,620
def list_objects(remote): """Return a list of object IDs for the current scene""" cmd1 = mmapi.StoredCommands() key1 = cmd1.AppendSceneCommand_ListObjects() remote.runCommand(cmd1) objects = mmapi.vectori() cmd1.GetSceneCommandResult_ListObjects(key1, objects) return vectori_to_list(objects)
bff6c73fad57af300add264f2314bcba5605b232
68,622
def site_details(site: dict) -> dict: """ Describe site details in a simple data structure designed to be used from SQL. """ return { "type": site.get("type"), }
12295cec8616fc9beb5d1d0e0b41e9ed5026a828
68,623
def cosmicray_lacosmic(ccd, error_image=None, thresh=5, fthresh=5, gthresh=1.5, b_factor=2, mbox=5, min_limit=0.01, gbox=0, rbox=0, f_conv=None): """ Identify cosmic rays through the lacosmic technique. The lacosmic technique identifies co...
67fdffa29c9c209ad62db167f3c88debcba26df4
68,624
import six def _check_dedup(data): """Check configuration for de-duplication. Defaults to no de-duplication for RNA-seq and small RNA, the back compatible default. Allow overwriting with explicit `mark_duplicates: true` setting. Also defaults to false for no alignment inputs. """ if dd.ge...
795ca9185c1ddb617609675af7143923369cd912
68,625
def y_intercept_line(slope, point): """ Calculate a y-intercept of a line for given values of slope and point. Parameters ---------- slope : float A value of slope line. point : tuple A tuple with xy coordinates. Returns ------- y-intercept : float A vaule o...
839cdaa4b4646ebbdc5a2b941e5e14b45587cd24
68,626
from operator import index def crawl(domain): """ Primary function for the process pool. Crawl websites for links to privacy policies. First check if the website can be reached at all, then find list of policy links on first page. Then loop through links to see if the links are valid polici...
ac55cc04c369a9a98d99d8813d0ab4856cdedc6b
68,627
import math import cmath def phasor_to_time(upha = 1+1j*0.0,uphb = -0.5-1j*0.867,uphc = -0.5+1j*0.867,w=2.0*math.pi*60.0,t=0.0): """Convert a,b,c quantities from phasor domain to time domain.""" ra,pha = cmath.polar(upha) rb,phb = cmath.polar(uphb) rc,phc = cmath.polar(uphc) #ua = (ra*np.exp(...
98b53a24c3ff22f25d8fe78b7dae3b6d426c01f9
68,628
def wepay_docs_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """ Process the WePay docs role. """ # get the application app = inliner.document.settings.env.app # parse the text entered in the role. # here, we simply split on space to define the two parts o...
3883f8b9437bd15c4aa3592ec23a6dcc56647f11
68,629
def followerstopper_example(render=None): """Perform a simulation of vehicles on a ring road. In this simulation, one vehicle is automated, and switches from human-driving to begins to automated vehicles after the time specified in AUTOMATED_TIME. Parameters ---------- render : bool, optio...
0e7b39c01b27c3cceff591735801fab17a46ca6e
68,631
def get_plugin_dir(app_path: str) -> str: """Returns full path to application plugin directory.""" product_info = get_product_info(app_path) version = parse_version(product_info.version) if is_android_studio(product_info): return join(ANDROID_STUDIO_PLUGIN_PREFIX, product_info.data_dir) if...
ad37618a10170e92407bdac16bacf7797dc5c407
68,632
from typing import Dict import types def makeSegmentLocations(seg, segSize): """ Create a data structure to hold the locations of all pixels in all segments. """ d = Dict.empty(key_type=types.uint32, value_type=RowColArray_Type) numSeg = len(segSize) for segid in range(MINSEGID, numSeg): ...
d8dcd8eb3d388a6e29c96c20865db2df3c711cff
68,633
def get_fasta_size(fasta): """ given a fasta file output the number of seqs and the length of the longest seq """ longest = 0 seqlist = read_fasta_file(fasta) for s in seqlist: longest = max(longest,len(s.seq.replace("-",""))) return len(seqlist),longest
f2e20ee41b2c67880582c8101cc75b6b4082627c
68,634
def random_email(): """随机email""" return fake.email()
3aa9f4a9bd23e6b49fe098d9280dfe3464b018fc
68,635
def load_pipeline(artifact_dir): """load all saved artifacts from pipeline run Args: artifact_dir (str): directory location Returns: pipeline: loaded pipeline components """ pipeline = PersistPipeline() pipeline.load(artifact_dir) return pipeline
2b1c3a559232abf3ee42121b8b7026d467010c5f
68,638
import torch def build_multi_agt_summarizer(n_agents: int, embedding_dim: int, vocab_size: int, hidden_size: int, n_contextual_layers: int, embeddings: torch.Tensor): """Builds the Multi-Agents Summarizer.""" embedding_layer = nn.Embedding.from_pr...
61d1c31440126cc179e49172cb35fb2e509d7b43
68,639
import json def iter_manifests(): """Iterate over all available manifests.""" manifests = [ json.loads(fil.read_text()) for fil in component_dir.glob("*/manifest.json") ] return sorted(manifests, key=lambda man: man["domain"])
9cfd93b07d3797bfdfb2c131d4a3d549d627fd96
68,640
def create_parent_record_links_bp(app): """Create parent record links blueprint.""" ext = app.extensions["invenio-rdm-records"] return ext.parent_record_links_resource.as_blueprint()
f977054140da7075daeb5ef1bb96dafd8164f537
68,641
def safe_dict(data): """Clean a dictionary to make sure it contains only valid, non-null keys and values.""" if data is None: return safe = {} for key, value in data.items(): key = safe_string(key) value = safe_string(value) if key is not None and value is not None: ...
b5ec44dc29c26b36517c2207daeed488acef61d2
68,643
def tp_group(tp_group_df, k): """Function called to find the top k for each time group""" #take the top k from each group tp_group_df = tp_group_df.head(k) #return the total tp in each group return tp_group_df['y_true'].sum()
b6cb7da179d7b5ad54b2d503ee107a2b922e1d8c
68,644
def fixture_async_message() -> AsyncMock: """Fixture""" message = AsyncMock() message.content = "<#!111> + <!222#> + Oh yeah baby!" message.guild.name = "Testing Guild" message.guild.id = 111 message.guild.owner.id = 333 message.author.id = 222 message.author.display_name = "Tester" ...
daa76ac9829ec7d18386b94681a701692f428c9e
68,645
def do_if_app(parser, token): """ An if statement that validates to True if an app is loaded. Example (the else tag is optional): {% if_app "tagging" %} <p>tagging is installed</p> {% else %} <p>tagging is not installed</p> {% endif_app %} """ bits = ...
b1296b5068106b80d918cdf07dfdd5ef1f4fe5b3
68,646
def get_client_ip(rq): """Try to get client's real IP address.""" x_forwarded_for = rq.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',') ip = ip[-1] else: ip = rq.META.get('REMOTE_ADDR') return ip
adae8af8841dad91fb1af9df196b3d424f53d33d
68,648
def band_atom_orbitals( folder, atom_orbital_pairs, output='band_atom_orbitals.png', spin='up', scale_factor=6, color_list=None, legend=True, linewidth=0.75, band_color='black', figsize=(4, 3), erange=[-6, 6], hse=False, kpath=None, n=None, fontsize=7, sav...
bfc5b589167494cd9e2a1de019fafdfb30897c76
68,651
def sherlockPredict(X: Matrix, cW1: Matrix, cb1: Matrix, cW2: Matrix, cb2: Matrix, cW3: Matrix, cb3: Matrix, wW1: Matrix, wb1: Matrix, wW2: ...
a9ed0c10c07f560588671cd585999da46a756cc8
68,652
import array def calculate_geomean(json): """ Extract all real/cpu times from all the benchmarks as seconds, and calculate their geomean. """ times = [] for benchmark in json['benchmarks']: if 'run_type' in benchmark and benchmark['run_type'] == 'aggregate': continue ...
b402022a31f0296676a3f1a9dc127d5f51c0aa37
68,653
import itertools def _groupby_leading_idxs(shape): """Group the indices for `shape` by the leading indices of `shape`. All dimensions except for the rightmost dimension are used to create groups. A 3d shape will be grouped by the indices for the two leading dimensions. >>> for key, idxs...
cc71304b9da4df2c9a32e009e3159bc9777d3e70
68,654
def _recvall(sock, size): """ Read exactly the specified amount of data from a socket. If a ``recv()`` call returns less than the requested amount, the ``recv()`` is retried until it either returns EOF or all the requested data has been read. :param sock: A socket from which bytes may be read....
6a456ee4925b7faa25646e9bc6e702848d047783
68,655