content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def dataframe_from_bulk(data, tz_offset): """ Create a Timeseries dataframe from a dict of ndarrays. Args: bulk_data(dict): tz_offset: pandas Offset or None Returns: pandas DataFrame object """ timestamp = pd.DatetimeIndex(data['timestamp']) if tz_offset is not None...
46e2a5d827ed9f6b698907acb8b8d7723e099e38
70,297
def get_label_map_dict(label_map_path, use_display_name=False, fill_in_gaps_and_background=False): """Reads a label map and returns a dictionary of label names to id. Args: label_map_path: path to StringIntLabelMap proto text file. use_display_name: whether to ...
8d960c230cf32f514ebbcfc211a5c004ce9620df
70,298
def eq104 (A, B, C, D, E, T): """Chemsep equation 104 :param A: Equation parameter A :param B: Equation parameter B :param C: Equation parameter C :param D: Equation parameter D :param E: Equation parameter E :param T: Temperature in K""" return A + B/T + C/(T**3) + D/(T**8) + E/(T**9)
57789dd811dc09bd097a52aca6a776b94ee05b95
70,299
from typing import Dict from typing import Optional from typing import Tuple from typing import Union def match_format( node: FormatNode, data: str, *, variables: Dict[VarName, VarDecl], values: Optional[Dict[VarName, Dict[Tuple[int, ...], Union[int, float, str]]]] = None, ) -> Dict[VarName, Dict[...
4d7cf10e7238f201c684e74f2f85d82ed9c52db3
70,300
def get_discussions(book_object): """ 获得本书所有的讨论 :param book_object: Book模型实例 :return: 本书所有讨论的列表 """ return book_object.discussions.order_by('-pub_date').all()
842a158a18e1e7a31579f409997d56a452f1cf61
70,301
def bagging_classifier(*args, **kwargs): """ same as in bagging_from_scratch() """ return BaggingClassifier(*args, **kwargs)
ac7965cc456c3a5f0722962ab779a5710dfe2b2c
70,302
def get_tool_path(folder, name, check=True, suffix=None): """Get tool path, returns pathlib.Path""" bin_dir = find_kit_dir('.bin') if not suffix: suffix = 'exe' name_arch = f'{name}{ARCH}' # "Search" tool_path = bin_dir.joinpath(f'{folder}/{name_arch}.{suffix}') if not (tool_path.exists() or name_arc...
37f398dfe0567db1d7b1125f1f7987bc76404db4
70,303
import google def load_tables(dataset, tablespecs): """Construct a dictionary of BigQuery tables given the input tablespec. Args: dataset: bigquery.Dataset tablespecs: list of strings of "NAME:DAYS", e.g. ["day:1"] Returns: client, {name: (bigquery.Table, incremental table name)} ...
9320488a9d0bdd3e15de4311d14c29cd1f295279
70,304
def get_last_shifts(user, count=5): """ Returns the last number of shifts of user :param user: User object :param count: Number of shifts to return. Default is 5 :return: Shift objects or None """ finished_shifts = Shift.objects.filter(employee=user, finished__isnull=False)[ :count ...
703998e841b3cf021219717e06409d01decb2317
70,305
def time_version(propagator, model, prop_kwargs=None, model_kwargs=None): """Measure the runtime of the specified version using the specified model. Args: propagator: The propagator object to use model: The model (such as one from test_scalar) to use Returns: Runtime in seconds ...
ec51e21c9392056352199b9f42db6c2211ff3f0a
70,306
def gen_service(cluster, bundle=None, prototype=None) -> models.ClusterObject: """Generate service of specified cluster and prototype""" if not prototype: bundle = bundle or gen_bundle() prototype = gen_prototype(bundle, 'service') return models.ClusterObject.objects.create( cluster=...
5b39a0d169f0a3d49c11d4ce9624212e0ee176b3
70,308
def compute_kepler_orbit( a, e, inc_0, omega, Omega_0, M_0, t, delta_n=0, inc_dot=0, Omega_dot=0, C_uc=0, C_us=0, C_ic=0, C_is=0, C_rc=0, C_rs=0, ref_sys='ECEF', GM=defaults.EARTH_GM(), ome...
51477f90f3c17223f4382aaf2e5b48d8079642fc
70,310
import logging def phoneme_is_ok(path_mono_align_lab, path_mono_score_lab): """ 音素数と音素記号が一致するかチェックする。 """ mono_align_label = up.label.load(path_mono_align_lab) mono_score_label = up.label.load(path_mono_score_lab) # 全音素記号が一致したらTrueを返す for mono_align_phoneme, mono_score_phoneme in zip(mono_...
4a65ef10aa15db9548a24cca2c7bebde57598d5d
70,311
from typing import Type from re import T from typing import Union def try_enum(cls: Type[T], val, default: D = None) -> Union[T, D]: """Attempt to convert a value into their enum value. Parameters ---------- cls: :class:`Enum` The enum to convert to. val: The value to try to conve...
4a5f25dbc2d71655388252aab40f71e332eeebdd
70,313
def SimInspiralNRWaveformGetRotationAnglesFromH5File(h5File,inclination,orb_phase): """ Compute the angles necessary to rotate from the intrinsic NR source frame into the LAL frame. See DCC-T1600045 for details. Implementation copied from https://github.com/lscsoft/lalsuite/blob/d6e071988b46ec4497a...
2551248ee7578cda998e47d4fb0c717b7f1fab5a
70,314
def char_cnn_model(x, y): """Character level convolutional neural network model to predict classes.""" y = tf.one_hot(y, 15, 1, 0) byte_list = tf.reshape(learn.ops.one_hot_matrix(x, 256), [-1, MAX_DOCUMENT_LENGTH, 256, 1]) with tf.variable_scope('CNN_Layer1'): # Apply Convolution fi...
3254a81f4030a4c661ccee40437a7da3f4275e80
70,315
def convert(root: 'TreeNode') -> 'TreeNode': """ 解法1:遍历两次。 """ if not root: return None inorder = [] def dfs(node): if node: dfs(node.left) inorder.append(node) dfs(node.right) dfs(root) for i, n in enumerate(inorder[:-1]): n.r...
a24d29d89459ec6be783fbc8d6f455665df7df68
70,317
import torch def batch_shuffle_ddp(x): # pragma: no-cover """ Batch shuffle, for making use of BatchNorm. *** Only support DistributedDataParallel (DDP) model. *** """ # gather from all gpus batch_size_this = x.shape[0] x_gather = concat_all_gather(x) batch_size_all = x_gather.shape[0...
6e49dbd4532054672d770d1f5825b13ce058a85d
70,318
def hostconfigurator(request, hosts): """Returns a configurator page with graphs on it""" stat, obj = parse() service_list = real_meta(hosts) return configurator(request, stat, obj, graphs=service_list)
272889a5e6cb9f37e0880853d0a13906fc186d9d
70,319
def process_args(*args, **kwargs): """returns a pair (artifact name, arg invocation)""" positional_kwargs = [] named_kwargs = [] for name in kwargs: if name.startswith('_'): positional_kwargs.append(name) else: named_kwargs.append(name) positional_kwargs.sort() named_kwargs.sort(...
a3ee66317b8309c7f49e543ece46bdb4024c5002
70,320
def create_graph(mdl, feature_names=None, cmap=None): """ Display a graph of the decision tree. Args: mdl (obj): Model used for prediction. feature_names (list): Names of the features. cmap (obj): Colormap. Returns: graph (obj): Graphviz graph. Example usage: ...
8e9131a2811e9eb32340fbd06d381df7e3d74f88
70,321
import json import html def build_alerts_elements(images_url_live_alerts, live_alerts, map_style): """ This function is used in the main.py file to create alerts-related elements such as the alert button (banner) or the alert markers on the map. It takes as arguments: - 'images_url_live_alerts':...
666c16029b73839107d0e9280416164a549ca565
70,322
import inspect def list_formatter(cls): """ This returns a function to map a given list of dictionaries to a list of class instances via a _from_dict class method. There is a corner case in which a passed in class might be a primative like a string. This also handles that case by skipping the...
a54f4c37a13343701133780dedc2dc3979cabde2
70,323
def get_edge_to_unique_attr(edgelist, src_col, dst_col): """Get a map from edge indexes to unique attribute indexes. Parameters ---------- edgelist : DataFrame Each row of the dataframe should contain the source, destination, and attributes of an edge. src_col : str Column name for ...
8d9c0a4871b9be6ba3f67eb6efc1cdbd711d18e8
70,324
def make_matrix_horizontal(l): """ Get the matrix with dimension 1*n needed for n*n masks, from an 1D list """ return np.array(l).reshape(1, -1)
345c1e075f6411f987b4edb34eb8bb1a92fe6612
70,325
def update_validator_registry(state: BeaconState, config: Eth2Config) -> BeaconState: """ Update validator registry. """ current_epoch = state.current_epoch(config.SLOTS_PER_EPOCH) # The active validators active_validator_indices = get_active_validator_indices(state.validator_registry, current_e...
934d378f5d299e98bed7a608fb3b1376cdaaf154
70,326
def membership_in_stream(in_stream, out_stream, membership_object): """ Parameters ---------- in_stream: Stream The input stream of the agent. Each element of the input stream is a pair: (function_name, string) where function_name is a string which is one of 'a...
8d145ef195da13f4e2078a661277b71deeecaf23
70,327
def _object_format(o): """ Object arrays containing lists should be printed unambiguously """ if type(o) is list: fmt = 'list({!r})' else: fmt = '{!r}' return fmt.format(o)
c71c0713d5b44c4733bc934d6026431e919db252
70,328
import copy def tensor_matrix_mult(X, V, n=None, Transpose=False, use_gpu=True): """ tensor_matrix_mult: Tensor times matrix. Parameters ---------- X: Tensor with N modes V: 2D array n: mode of tensor X to which to multiply the matrix by Transpose: Should we ro...
22a76d58909cb2b1213a3c2a5bb42d784bf7758a
70,329
import traceback def handle_error(error): """Error handler when a routed function raises unhandled error""" print(traceback.format_exc()) return 'Internal Server Error', 500
d93d3c4bbabb578b28ade961bb46793187a5ee06
70,330
def cifar100_rnn_gate_74(pretrained=False, **kwargs): """SkipNet-74 with Recurrent Gate""" model = ResNetRecurrentGateSP(BasicBlock, [12, 12, 12], num_classes=100, **kwargs) return model
2f4d40f804237972364bcd322ce3a6c6d8261ea0
70,331
def appliance_status_json(): """ Appliance Status JSON call :return: """ return jsonify(verify_appliance_status())
93a117a20f602e05b34bdf8df70e9c0784422708
70,332
import numpy def equalization(img): """ Função que equaliza o histograma :param img: a imagem a aplicar a equalização :return: O histograma equalizado """ h,r = numpy.histogram(img, bins=256, range=(0, 256)) p = h/float(dim[0] * dim[1]) pa = numpy.cumsum(p) pa_norm = pa*255 equ...
02d55f2dd848848062d340fccb5a8aede4ee6c9f
70,334
from typing import Optional def filter_by_chart( chart_filter_pattern: Optional[FilterPattern], chart_name: str ) -> bool: """ Return True if the schema needs to be filtered, False otherwise Include takes precedence over exclude :param chart_filter_pattern: Model defining chart filtering logic ...
22e24e91eb85bc4cdcc1bdb638eea9c008bcde6e
70,335
def get_agencies_dict(agencies_file): """ Pulls agencies list into a dictionary for use in abbreviations pipeline. Args: agencies: file of the agency documents. currently set to agencies.csv Returns: dictionary of all agencies """ df = pd.read_csv(agencies_file) aliases = {...
eb80f30f570913959b63c0bc8a215d9d7942b19e
70,336
def compute_batch_indices(batch_size, k): """ Computes the i'th coordinate that contains the batch index for gathers. Batch pos is a tensor like [[0,0,0,0,],[1,1,1,1],..]. It says which batch the beam item is in. This will create the i of the i,j coordinate needed for the gather. Args: bat...
d342ced62fc776b78ff940be55c05497639d5897
70,337
def _set_conditions(condition_list): """Returns an argument for config_settings that sets specific options. Args: condition_list: a list of three booleans Returns: a dictionary parameter for config_settings such that ":conditionN" is True iff condition_list[N + 1] is True """ ...
a1d4443a8f638754d8ece8692ab702f80670c09a
70,338
def getAvgEvalScores_ofTrainRuns(nr_runs,X_train,y_train,ID_train,label_dict, scores_list, print_flag): """ Get the average scores of the specified score list from a number of runs. Args: nr_runs (int): number of runs. X_train (dataframe of features, once removed the columns of label an...
6ceeb648463a88cf0cc671c65049ab82196830b1
70,339
import colorsys def scale_lightness(rgb, scale_l): """ Scales the lightness of a color. Takes in a color defined in RGB, converts to HLS, lightens by a factor, and then converts back to RGB. """ # converts rgb to hls h, l, s = colorsys.rgb_to_hls(*rgb) # manipulates h, l, s values and retu...
2fee635f26419cfe8abc21edb0092a8c916df6ef
70,341
def get_hw_type_from_client(hw_client) -> HWType: """ Return hardware wallet type (HWType) based on reference to a hw client. """ if hw_client: t = type(hw_client).__name__ if t.lower().find('trezor') >= 0: return HWType.trezor elif t.lower().find('keepkey') >= 0: ...
02946f1284705bc06e89874f240b0dbfb93b5f55
70,342
def kmeans(X, n_features, batch_size, n_iterations, verbose=False): """ Finds kmeans for X. Parameters: X: 2D matrix with shape: (n_samples, dimensions) config: n_features: number of centers (k). NOTE: the final k can be less than n_features since this code ...
29a0c8f378c22f77dc699e3b87ceffa0b4391779
70,343
def fit_linreg_robust(x, y, mask=None, intercept=False, r2=True, est_method='rlm'): """Apply robust linear regression of y w.r.t x. Arguments --------- x: :class:`~numpy.ndarray` or sparse `csr_matrix` A vector of independent variables. y: :class:`~numpy.ndarray` or sparse `csr_matrix` ...
6b6372a2aa0a7239b7e3598c8972f25fea62260b
70,344
def emg_process(emg, sampling_rate=1000, emg_names=None, envelope_freqs=[10, 400], envelope_lfreq=4, activation_treshold="default", activation_n_above=0.25, activation_n_below=1): """ Automated processing of EMG signal. Parameters ---------- emg : list, array or DataFrame EMG signal array....
bd95e1a8708bce5fda3ca7c5274363faa2bcea36
70,345
def peek(src: TextIOBase, n: int = 1) -> str: """Read up to `n` bytes from `src` without advancing the offset""" with peeking(src): return src.read(n)
5975dc8c94c262e700281120c81eb936adf677d6
70,346
def generate_key(**kwargs): """ Generates a new RSA private key. :param size: :param key_gen: :param kwargs: :return: """ key_gen = kwargs.get("key_gen", default_key_gen) return key_gen(**kwargs)
ae8355e4a3dfc62af24c947b3526b0892ea36d03
70,347
import torch def dummy_compute() -> torch.Tensor: """ returns a predefined size random Tensor """ return torch.rand(100, 100)
9b1c05359c9b57573bd2771124e878ccee7eae87
70,348
import typing def validator(*kinds: typing.List[str], collect=True, raise_on_invalid_kind=False) \ -> typing.Callable: """ decorator to generate validator functions. Expects LintError exceptions on invalid configurations. """ def add(f: typing.Callable): @wraps(f) ...
baee56ab9d7ed2aa9f538567e75d11f189d9c708
70,349
def mlp_net_input(h, w, b): """ Return the network input z as a function of h, w, and b. :param h: the input from the previous layer. :param w: the weights for this layer. :param b: the biases for this layer. :return: the linear network activations for this layer. """ result = np.dot(h, ...
21c035ea5c8704d27bd53e22cd253113cd602e61
70,350
import json async def get_schedules_handler( request: Request, ip_address: str, phone_id: str, device_id: str, device_password: str, ) -> HTTPResponse: """Use for handling requests to /switcher/get_schedules. Args: request: ``sanic``'s request object. ip_address: the local ip ...
14e54ec0872689a7730e6c9b26de4bf100423ea4
70,351
def extractPrefix(x, prefix_length, as_string): """ Returns an IPNetwork object of the ipaddress module created using ip address `x` given as string with a prefix length of `prefix_length` x (String): ip address prefix_length (int): number of bits to use as a prefix as_string (boolean) : ...
4fa68867ebebac28b2fd69fd7b33146be81e2fa3
70,352
def vel_distance(v1, v2, theta): """ Velocity distance. The Equation (2) of Mould et al. (2000). Parameters ---------- v1 : float The velocity of the first object, units: km/s. v2 : float The velocity of the second object, units: km/s. theta : float The angular dist...
f34354d6f8ef6c731c329524db9fbcefe4bb1ba9
70,354
def for_list_lang(context): """Вывод списка языков""" return settings.LANGUAGES
081a0ee93ce0901827407abeb711f6763dc67eb7
70,355
def raster2array(rasters,band_no=1): """ Arguments: rast A gdal Raster object band_no band numerical order Example : raster = gdal.Open(rasterfn) raster2array(raster,1) """ bands = rasters.RasterCount if band_no>0 and band_no <=bands: band = rasters.Get...
76bdcffbf22a0936fe24c29eba975f21edd7cd41
70,357
def early_stopping(cost, opt_cost, threshold, patience, count): """ Determines if you should stop gradient descent. Early stopping should occur when the validation cost of the network has not decreased relative to the optimal validation cost by more than the threshold over a specific patience count ...
5baea9f867e8ca8326270f250327494a5c47af46
70,358
def search(): """search for a specific item""" searchword = request.args.get('search', '') json = request.args.get('json', '') if not json: # if the user didn't provide a search word return error message. if not searchword: return render_template("mes.html", error="must prov...
adeff4717d9884a6c903aa7aeb10c0f22e40df06
70,359
def diameter(domain): """ Returns the diameter of a domain. :param domain: a domain :type domain: `escript.Domain` :rtype: ``float`` """ return sqrt(sum( [ v**2 for v in boundingBoxEdgeLengths(domain) ] ))
8fe13ecf19f96ea624f0a2d20f165033593bc3ad
70,360
import asyncio def chain_execution(commands): """ Executes given commands sequential. If one commands fails all other commands fail too. """ result = [] error = False for command in commands: try: cmd = Command( command["method"], uuid=c...
d06be2a3f9395343be5787d248e95e1996b9ec9a
70,361
import json def export_roast(): """Export a roast log.""" c = mongo.db[app.config['HISTORY_COLLECTION']] roast_id = request.args.get('id') roast_id = paranoid_clean(roast_id) item = c.find_one({'_id': ObjectId(roast_id)}, {'_id': 0}) if not item: return jsonify({'success': False, 'mess...
deb25421561c6e66782c351ccfa4f6b82f94e898
70,364
def tagset_mapping(source, target): """ Retrieve the mapping dictionary between tagsets. >>> tagset_mapping('ru-rnc', 'universal') == {'!': '.', 'A': 'ADJ', 'C': 'CONJ', 'AD': 'ADV',\ 'NN': 'NOUN', 'VG': 'VERB', 'COMP': 'CONJ', 'NC': 'NUM', 'VP': 'VERB', 'P': 'ADP',\ 'IJ': 'X', 'V':...
fc1acd0d33dc201b1d692e84c1469d1899488f53
70,365
def generate_launch_description(): """Run demo nodes via launch.""" return LaunchDescription([ launch_ros.actions.Node( package='pub_sub_tests', executable='talker', output='screen', remappings=[('chatter', 'my_chatter')]), ])
578f9763da52cb8991f07c9e2f6a865069a170c3
70,367
def get_features(contour): """Get the three features that identify a corner marker""" try: return (cv2.contourArea(contour), cv2.arcLength(contour, True), cv2.contourArea(get_bounding_rect(contour))) except ZeroDivisionError: #return 4*[np.inf] return ...
54bfa67d8bc59b145ef93bc3ee29b00665e4c8ce
70,368
import re def _MatchStaticFile(handler, path): """Match a path to a regular expression and return a StaticPage. Args: handler: A handler dictionary with a static_files field. path: The path portion of the url. Returns: A StaticPage object or None. """ pattern = handler['url'] if not pattern....
2dca79df358d0c51710f8d559d7d23139b8a378b
70,370
def apply_non_max_suppression(boxes, scores, iou_thresh=.45, top_k=200): """Apply non maximum suppression. # Arguments boxes: Numpy array, box coordinates of shape (num_boxes, 4) where each columns corresponds to x_min, y_min, x_max, y_max scores: Numpy array, of scores given for ea...
5651577e32a7dbb23400e354ff6527fbdb785a7c
70,371
def get_default_configuration(invocation_id, config_id=None): """ Returns a new Configuration with fields initialized to defaults. Args: invocation_id (str): The id of the invocation for the configuration. config_id (str): The id of the configuration. Returns: A new Configurati...
d5a82349bc5031869e919b2bee859b11a022362b
70,372
def cosh(input, name=None): """Element-wise hyperbolic cosine of a tensor.""" if is_tensor(input, 'tf'): return tf.math.cosh(input, name=name) else: return np.cosh(input)
aec39ba69b6c3836114338564fdde3b149e2b86b
70,373
def blockwise( func, output, output_indices, *arrind_pairs, numblocks=None, concatenate=None, new_axes=None, dependencies=(), **kwargs, ): """Create a Blockwise symbolic mutable mapping This is like the ``make_blockwise_graph`` function, but rather than construct a dict,...
0433678321afbff5d999185a98de6bdfb2a6f59f
70,374
def extract_biofuel_shares_from_IAM( model, fp, IAM_region, years, allocate_all_synfuel=False ): """ This function extracts biofuel shares from a IAM file provided. :param fp: file path to IAM file :type fp: str :param IAM_region: IAM region for which to extract the biofuel shares :type IAM...
372412f6e2355cf8cc9c0c7ab19dac4b234d7668
70,376
def blendLayers( background: Image.Image, foreground: Image.Image, blendType: BlendType | tuple[str, ...], opacity: float = 1.0, ) -> Image.Image: """Blend layers using numpy array. Args: background (Image.Image): background layer foreground (Image.Image): foreground layer (must be same size as background) ...
df352c3d9bff6a7972a98984b8e032408bb5ac22
70,378
import importlib def class_from_class_path(class_path): """ Get a python class instance given the python "class path". EG: # >>> class_from_class_path("decimal.Decimal") # <class 'decimal.Decimal'> Args: class_path - str - dot-delimited python path followed by class name. Returns: class...
5584c827da786dec73b85026289a0580214d022d
70,379
def is_if_then(tokens): """:note: we assume single-line if have been transformed in preprocessing step.""" return tokens[0:1+1] == ["if","("]
aa1a946ed94299e689534ca98dcf1d0fa9bdca32
70,381
def get_implline(cursor: Cursor) -> int: """ finds the first line of implementation source code for class method pointed by the cursor parameter. Args: cursor: libclang cursor pointing to the target mock class definition. Returns: an integer, the line number of the first line of the correspondi...
ad1fe32e6dba22a42ee2da0295e95490288e5daf
70,384
def inverse_dissim(X): """ :param X: int or np.array :return: """ X = np.asarray(X) X = zscore(X) X = minmax(X, 0, 10) return 1./(1+X)
87737ba4d425bb91d58060ef4aa535010099d002
70,385
import yaml def yaml_load(file): """ Load single-document YAML and return document """ with open(file, "r") as f: return yaml.safe_load(f)
76402fd742f5aaf1776751f44b3583a62c1f3581
70,386
import time def is_available(workshift_profile, shift): """ Check whether a specified user is able to do a specified workshift. Parameters: workshift_profile is the workshift profile for a user shift is a weekly recurring workshift Returns: True if the user has enough free time...
a847e3d7e91d4272c035a9a8dd609e20a0247b8a
70,387
def BuildEdgeFunction(function_ref, arch, source, function): """Calls Cloudbuild to build Edge Function. Args: function_ref: Edge function resource arch: str, target architecture, should be one of 'x86-64', 'armhf', or 'aarch64' source: str, GCS URI of source provided from command line functi...
f18c90a3db684b847bd3de2289802599e916656f
70,388
def convert_event_data_timestamp(ts): """ Convert the default event_data timestamp format to Pandas and unixtime format. Parameters ---------- ts : str UTC timestamp in custom API event data format. Returns ------- timestamp : datetime Pandas Timestamp object format. ...
99f4604b4a1c5d164dfcf4567c85fcf12e149337
70,389
import tempfile import zipfile def unzip_csar_to_tmp(zip_src): """ Unzip csar package to temp path :param zip_src: :return: """ dirpath = tempfile.mkdtemp() zip_ref = zipfile.ZipFile(zip_src, 'r') zip_ref.extractall(dirpath) return dirpath
b6be57f4e20c208583cc15dc9d0b997f6b41e2f1
70,390
import time from re import L def integrate_verlet(X, V, iparams, blist, sp): """ Verlet integration for Nt steps. Save each thermo-multiple step into xyz_frames. Mass set to 1.0. Input: * X: (N, 3) matrix * V: (N, 3) matrix * iparams: (Nbt, Nbt) matrix with interaction params * blist: ...
e9b60a294e257a87461afe8f745f61083f4a1075
70,391
import torch def seq_collate_fn(batch): """ Returns several tensors. Tensor of lengths should not be sent to CUDA. """ idx2batch = pd.Series(np.arange(len(batch)), index = [b["idx"] for b in batch]) df = pd.concat(b["path"] for b in batch) value_cols = [c.startswith("Value") for c in ...
2a1fcbd3ce386f5cc9b6851359ac7ade0d0e979a
70,392
def get_device_fn(device): """Choose device for different ops.""" OPS_ON_CPU = set(get_cpu_list()) def _device_fn(op): # Startswith "Save" is a hack... if op.type in OPS_ON_CPU or op.name.startswith('save'): return '/cpu:0' else: # Other ops will be placed on...
fe7993d624d38f003311c4a7d1b010af5320c6f8
70,394
def handle_element(elem, args, func=None, func2=None): """ A helper function to handle elements from BeautifulSoup element.find() :param elem: BeautifulSoup Tag (element) :param args: args tuple for find method. String can be used for a single arg, otherwise tuple :param func: ad hoc fun...
7f63b4ec8f762bfdf427328eeec05846504ee8d8
70,395
def add_columns(input_header, input_rows, column_names, fill_with="NULL", in_place=True): """Add new columns filled with the requested value Parameters: input_header (list): List of column headers from input file input_rows (list): List of lists of fields from each i...
12979c354c0031f1ebc5f17d229a09dc59b020d3
70,396
from datetime import datetime def date2datetime(dt): """ date 类型转换问 datetime类型 :param dt: :return: """ return datetime(dt.year, dt.month, dt.day)
53bf2cabe3d8a70791cb92fb12387a78d0beedd7
70,397
import re def splitSentence(content): """ Given block of text, split into sentence Output: list of sentences """ # Multiple space to single space, remove separators like - and _ if pd.notnull(content): content = re.sub('\s*\t\t\t', ' ', content) content = re.sub('--+|==+|__+', ...
85a4eea6928f689b87a60edd2d4fe47b9f6d0a15
70,398
def save_data(outpath, header, row, data): """ Simple shortcut If `feather-format` is available, save data to `.feather` file otherwise `.csv` """ try: return save_data_to_R(outpath, header, row, data) except ImportError as e: return save_data_to_csv(outpath, header, row, data)
17e59bad3e68cab15b40d6e229c09842b62df3fe
70,399
from typing import Callable from typing import Any from typing import List import inspect def get_parameters( f: Callable[..., Any], allow_args: bool = False, allow_kwargs: bool = False ) -> List[str]: """Get names of function parameters.""" params = inspect.getfullargspec(f) if not allow_args and par...
218e187ae504ce18c0d240aee93480e275f4b8a4
70,400
def error_417(message = None): """JSON error handler for HTTP error 417""" if not isinstance(message, str) or len(message) < 1: message = 'Expectation Failed' return _error(code = 417, message = message)
d72965ccd49c9e8d679dadde74d2ab76a0ea005b
70,401
from typing import Optional from typing import Generator def barabasi_albert(num_nodes: int, num_edges: int, rng: Optional[Generator] = None) -> NDArray: """ Returns a graph sampled from the Barabasi-Albert (BA) model. The graph is built incrementally by adding `num_edges` arcs from a new node to already ...
c1df5d4dfd29a2c7eabc2159d611d2186415c1d8
70,402
import functools def split_and_combine_df(func=None, *, remove_type=False): """Split the data across sub state spaces and combine. This function groups the data according to the dense variables. `remove_type` is used to prevent grouping by types which might not be possible. """ def decorator_sp...
a472c9dff37dc2144b5938bdaf196fcb7cc2e514
70,403
import ctypes def get_output_console_level(p_state): """Returns the level up to which the Log is output to the console. The return value will be one of the integers defined above. """ return int(_Get_Output_Console_Level(ctypes.c_void_p(p_state)))
0363de51919b6e09a6de6ad905967d62878be448
70,404
def create_beam_node(instrument, bounds, visible=False): """Creates node for beam :param instrument: instrument object :type instrument: Instrument :param bounds: bounding box of the instrument scene :type bounds: BoundingBox :param visible: indicates node is visible :type visible: bool ...
b6d7476498f68d5bf90141f0d2123c21f8cef4a7
70,405
def svn_diff_mem_string_output_unified(*args): """ svn_diff_mem_string_output_unified(svn_stream_t output_stream, svn_diff_t diff, char original_header, char modified_header, char header_encoding, svn_string_t original, svn_string_t modified, apr_pool_t pool) -> svn_error_t """ re...
2f20e704eb848b338268fff01bcbfb82c3a843dd
70,406
def annotate_with_clonality(insertions): """Annotates an insertion dataframe with the clonality of insertions. The clonality of each insertion is calculated by dividing the support of the insertion by the support score of the strongest insertion in the same tumor. Parameters ---------- ins...
b78d770d0f295912859d375b0b974276e2704cf1
70,407
def _convertCtypeArrayToList(listCtype): """Returns a normal list from a ctypes list.""" return listCtype[:]
89a408b796f2aba2f34bc20942574986abd66cd2
70,408
def expr_len(e: Expression) -> int: """ Computes the number of nodes in the AST of `e`. :param e: The expression whose length is computed. :return: The length of the expression. """ return 1 + sum(map(expr_len, e.children()))
c26355a56ce94c2f18a57d59d92c0bfe154355a9
70,409
def read_datafile(filename): """ Reads a langmuir csv file with the format: time,header,Sweep voltage,Plasma voltage,Plasma temperature,Particles counter 2018-07-19 07:03:48,0x43434301,4.017525,4.1494875,291.78375,2 # Calibration 2018-07-19 07:03:48,0x43434302,4.0126375,3.470125000000...
6bf3f0ded56563086ccd8f39aaeab23d3a233369
70,410
def selectFood(): """Display caterering options""" t = TenativeBooking.loadFromSession() d = Dish.select().where(Dish.isDeleted == False) c = Caterer.select().where(Caterer.isDeleted == False) dishes = prefetch(d, c) return render_template('event/caterer.html', dishes=dishes, booking=t)
429e5e990f28a7954e50c3e440aa7d6bcbcb6eb8
70,411
from typing import List def get_cost_vector(counts: dict) -> List[float]: """ This function simply gives values that represent how far away from our desired goal we are. Said desired goal is that we get as close to 0 counts for the states |00> and |11>, and as close to 50% of the total counts for |01> and...
b7565de2e47ba99e93b387ba954fdc29f44805e8
70,412
def YcCbcCrc_to_RGB(YcCbcCrc, in_bits=10, in_legal=True, in_int=False, is_12_bits_system=False, **kwargs): """ Converts an array of *Yc'Cbc'Crc'* colour encoding values to the corresponding *RGB* array of lin...
b730dadfc38a1ad96f7ec0e795020b3239f1fcd8
70,413
import sqlite3 def getradecrangedb(dbfile): """ Get RA/DEC ranges from database """ sqlite3.register_adapter(np.int16, int) sqlite3.register_adapter(np.int64, int) sqlite3.register_adapter(np.float64, float) sqlite3.register_adapter(np.float32, float) db = sqlite3.connect(dbfile, detect_types=...
84553ab1a284b253026f1ae6d99e9ad4d7922c63
70,415