content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def a2str(a): """ formatting for 1 or 2 dimensional numpy arrays of booleans """ if len(a.shape) == 1: return "".join(map(str, a)) elif len(a.shape) == 2: return "\n".join(map(lambda row: "".join(map(str, row)), a))
589cbc72bc1c3379f74a924f14b304d91a517157
3,619,732
def find_PFd(A, B, Q, R, beta=.95): """ Taking the parameters A, B, Q, R as found in the `setup_matrices`, we find the value function of the optimal linear regulator problem. This is steps 2 and 3 in the lecture notes. Parameters ---------- (A, B, Q, R) : Array(Float, ndim=2) The ma...
30c4085ba99eac914f718495589e37dace74e639
3,619,733
def _should_save_cookies(request): """ Return True if cookies should be saved for a request """ # based on QNetworkReplyImplPrivate::metaDataChanged() C++ code attr = request.attribute( QNetworkRequest.CookieSaveControlAttribute, QNetworkRequest.Automatic ) return attr == QNetworkReq...
3b24f363e8dfecf227eb16c8fdbf3138938be800
3,619,734
import json def generate(data_path, registry): """generates templates based on arguments and configurations.""" if not current_folder_has_venv(): logger.warning(Text.no_virtual_environment_remainder) with open(data_path / "category_tree.json", encoding="UTF-8") as file: full_tree = json....
6d630513c317869603d23110f72839cd68975ffd
3,619,735
import signal def get_maxima( series, N, start_date = None, stop_date = None, _sorted = True ) : """ Summary: Function that determines the first N maxima of a pandas time series Arguments: series - pandas series N - number of maxima start_date - start date as DateT...
7f006c3ce795b8ad46f2a30d718fbab51cfd7515
3,619,737
def get_latest_challenge_from_player_id(player, should_be_completed=False): """ Tries to find the latest challenge belonging to a player param int player: The player ID to search the challenges for param bool should_be_completed: If the challenge should already be completed or not returns os3_rll.m...
9408cde081714d3994dbc9286ca699354a5f3bd1
3,619,739
import torch def runepisode(env, policy, episodesteps, render, windowlength=4): """Runs an episode under the given policy Returns the episode history: an array of tuples in the form (observation, processed observation, logprobabilities, action, reward, terminal) """ observation = env.reset() ...
ef50ac2b2afd6912d27930ae7b5a1101f3d31776
3,619,740
def lookup_linear_velocity( frame, reference=None, represent_in=None, outlier_thresh=None, cutoff=None, as_dataarray=False, return_timestamps=False, ): """ Estimate linear velocity of a frame wrt a reference. Parameters ---------- frame: str or ReferenceFrame The ref...
fb6ab94b4f5dea3a96e08bfc854bacaa3b14a34f
3,619,741
def dispatch_slug_path(*views): """ Dispatch full path slug in iterating through a set of views. Http404 exceptions raised by a view lead to trying the next view in the list. This allows to plug different slug systems to the same root URL. Usages:: # in urls.py path('<slug:slu...
570402f4461aaf033bc8abafedbaae15c2ef7efd
3,619,742
def applyFxToVolumes( ts, vols, fx, **kwargs ): """ Apply a function on selected volumes of a timeseries. 'ts' is a 4d timeseries. It can be a NiftiImage or a ndarray. In case of a ndarray one has to make sure that the time is on the first axis. 'ts' can actually be of any dimensionality, but datasets ...
32b24975292f228a28584f146023e051a5da4453
3,619,743
def getTrack ( tleFile, t_beg, t_end, dt_secs=60): """ Given a Two Line Element (TLE) file name, a time interval, returns tuple with (lon,lat) coordinates of satellite ground track. """ dt = t_end-t_beg n = 1 + int(dt.total_seconds() / dt_secs) Dt = timedelta(seconds=dt_secs) nymd =...
26f82a409f9f01cc738b93b98b1affc6843332a3
3,619,744
def __read_dataset_item(path): """Reads data set from path returns a movie dict. Parameters ---------- path : str Absolute path of the MovieLens data set(u.data). Returns ------- rating_dict : dict Returns a dict of users, movies and ratings....
a87baecc5b0c28675bc715aab646bf41e4b40f96
3,619,745
import logging import time def wait_for_new_checkpoint(checkpoint_dir, last_checkpoint=None, seconds_to_sleep=1, timeout=None): """Waits until a new checkpoint file is found. Args: checkpoint_dir: The directory in which check...
ee355f2e55cc8a714c6d4e523615b2508589f1df
3,619,746
def get_data(data_fn, param): """Feed data_fn with param """ return data_fn(**merge_dicts(param["data"], param.get("shared", {})))
605e29d8e45967f3d938dd094c233d5b36ae6aa9
3,619,748
def get_heat_flow_3(matrix_temp: np.ndarray, param: Parameters) -> float: """ 各部温度から断熱材+内装材伝導熱量を計算する :param matrix_temp: 各部温度計算結果 (5,1), degC :param param: 計算条件パラメータ群 :return: 断熱材+内装材伝導熱量, W/m2 """ return param.C_2 * (matrix_temp[2] - matrix_temp[3])
9af08c218351d51bec890635abcce301cd83b8f1
3,619,749
def create_training_label(center, size, corners, resolution=0.50, scale=4, x=(0, 90), y=(-50, 50), z=(-4.5, 5.5)): """Create training labels which satisfy the range of experiment""" min_value = np.array([x[0], y[0], z[0]]) xyz_logical = judge_in_voxel_area(center, x, y, z) center[:, 2] ...
be6139bc4b5665194afc890fcce474d3d13ce872
3,619,750
import urllib import re def proxy_list_from_free_proxy_list_net(): """ will connect to https://free-proxy-list.net/ and will get the proxy list from that page proxy format : ip address, port """ link = 'https://free-proxy-list.net/' regex = '<td>(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})<...
6f8721331024a85f5e406e36557ffdddacd7654d
3,619,751
def adv_training(sess, inputs, labels): """Train and evaluates a model on adversarial examples """ adversarial_model = get_model(FLAGS.model_type, 'train_adv') fgsm2 = FastGradientMethod(adversarial_model, sess=sess) def attack(inputs): return fgsm2.generate(inputs, **ADV_CONSTANTS.get_attack_details(FLA...
088595fe5a7ab681f25ea7149017eba4555353cd
3,619,752
def unifiable(cls): """ Register standard unify and reify operations on class This uses the type and __dict__ or __slots__ attributes to define the nature of the term See Also: >>> class A(object): ... def __init__(self, a, b): ... self.a = a ... self.b = b >>> un...
48e4cbc5373dc445923e47c8c8f65e99a035b338
3,619,753
def kMeansInitCentroids(X, k): """ 初始化 cluster centroids :param X: :param k: :return: """ m = X.shape[0] centroids = np.zeros((k, X.shape[1])) m_arr = np.arange(0, m) np.random.shuffle(m_arr) rand_indices = m_arr[:k] centroids = X[rand_indices, :] return centroids
d6aa56fb1157ff9bdc2cf82bb7864b08ef471dc1
3,619,754
from typing import AnyStr from typing import List from typing import Dict def get_metric_rating_max(metric: AnyStr, start: AnyStr, end: AnyStr, tenant_id: AnyStr, namespaces: List[AnyStr]) -> List[Dict]: """ ...
33971a0f846a0bcb40b0acf16b32fc62a5bfefb1
3,619,755
def generate_binary_random_number(size=1): """Generates a binary random number or array based on an uniform distribution. Args: size (int): Size of array. Returns: A binary random number or array. """ binary_array = np.round(np.random.uniform(0, 1, size)) return binary_array
3833115e82b87a9773f53046d6dc6114febdc56f
3,619,756
def make_class(any, base=data.module.YO, *args, **kwargs): """check base is correctly resolved to Concrete0""" class Aaaa(base): """dynamic class""" return Aaaa
d0729d5f50e656a2fd76eda02d7d07ebd4682162
3,619,757
from typing import Optional def make_nbh_test(station: str) -> Optional[dict]: """Builds NBH test file for station""" return make_forecast_test(avwx.Nbh, station)
761db3a8587e852dd9048eb3dd12cc64ecd7e8c1
3,619,758
def get_manifest_indexes(manifest, channel, column): """Get the indices for channel and column in the manifest""" channel_index = -1 for x in range(len(manifest["channels"])): if manifest["channels"][x]["channel"] == channel: channel_index = x break if channel_index == -1...
63d82417b1e106d408866933bce776c272b2e77d
3,619,759
from typing import List def get_function_call(fn_to_call: ts.FunctionType, argument_names: List[str], fc: context.FunctionContext): """ DOES NOT COPY stack symbolic registers! argument_names should be located in stack symbolic registers [argument_names] RETURNS a stack symbolic register which th...
dace1b83478e8750518878ac0be77fb24393ef0f
3,619,760
def parse_training_args(args=None, ignore_unknown=False): """parser for training script""" arg_populate_funcs = [training_args, custom_mlp_args] arg_check_funcs = [process_training_args] return parse_various_args( args, arg_populate_funcs, arg_check_funcs, ignore_unknown )
93fdd653199873c9cb32b5f6b7f63ae22a21f057
3,619,762
import torch def query_ball_point(radius, nsample, xyz, new_xyz): """ Input: radius: local region radius nsample: max sample number in local region xyz: all points, [B, N, 3] new_xyz: query points, [B, S, 3] Return: group_idx: grouped points index, [B, S, nsample] ...
e74992747103d11b6618ecf7daf035c4f83e9911
3,619,763
import math def get_num_blocks(content_length, block_size=DEFAULT_BLOCK_SIZE): """ Split file of specified length into blocks """ return int(math.ceil(content_length / block_size))
e39f20c48f4dbd4f4baaf150bd35122b49ad5b30
3,619,764
def is_bounded(coord, shape): """ Checks if a coord (x,y) is within bounds. """ x, y = coord g, h = shape lesser = x < 0 or y < 0 greater = x >= g or y >= h if lesser or greater: return False return True
0a0b6921fcdf285c89b5021d113585ff38255013
3,619,765
def perp2coast(X1,X2,Y1,Y2,X0=0,Y0=0,hip=10000,deltahip=1000,units='m',side=1): """ INPUT: X1: Initial point in X for compute slope X2: Final point in X for compute slope Y1: Initial point in Y for compute slope Y2: Final point in Y for compute slope X0: Point to colocate the slope in X ...
9836150c3aa3d2c5cae9aec62d47401cbd542d02
3,619,767
def conv2d(input_, W_shape, name, reuse=False): """ name - layer name for variable scope W_shape - [height, width, input_layers, output_layers] """ # 在名称空间name下添加变量Variable,但最好传递一个reuse参数。 with tf.variable_scope(name, reuse=reuse): # 对convolution层的权值参数 W 和 b 进行初始化 W_conv = tf.get_var...
e4ac8a798a49ed9ffc14f83b44704119f5f7f0fb
3,619,768
import re import requests from bs4 import BeautifulSoup import time def get_one_postalcode(ps='00100', onSale=True): """ Perform the query on one postal code. QUERY TESTED: 13.11.2019 :param ps: the postal code to query. :param onSale: bool, if true do the query sales, if false do the query on ren...
fb0b070121878b5bf5304b9e1712e87e8195a771
3,619,769
def CV_ARE_SIZES_EQ(*args): """CV_ARE_SIZES_EQ(CvMat mat1, CvMat mat2) -> int""" return _cv.CV_ARE_SIZES_EQ(*args)
b559f7e849c36b9f1683d8c0a2562aa5640a6b21
3,619,770
def sph2car(theta, phi, radius=1.0): """ Transform the spherical coordinate to cartesian 3D point. :param theta: longitude :type theta: numpy :param phi: latitude :type phi: numpy :param radius: the radius of projection sphere :type radius: float :return: +x right, +y down, +z is fr...
1397983ca6ae42280603109ad28f49f41361539c
3,619,771
from re import T def expand_range_spec( spec: T.Union[int, str], min_value: int, max_value: int ) -> T.Set[int]: """Expands strings of the range specification format to RangingSet objects containing the individual numbers. Any whitespace is ignored. If an int is given instead of a string, a set co...
c6a3c2550126cc4ff8d4553ef1471d0edfb9b3b3
3,619,772
from typing import Dict import requests def get_tasks_by_project_id(workspace_id: str, project_id: str, api_key_header: Dict) -> Dict: """Get tasks associated with a given project ID and workspace ID. This function returns a dictionary of tasks corresponding to a given project ID and workspace ID...
3141b04424c87408e1c155e31c81c8f87a5ee0d1
3,619,773
def checksum_file(path: str) -> str: """ Gets the checksum of a file Parameters ---------- path : str The path to checksum Returns ------- string Checksum """ message = PrettyStatusPrinter("Getting MD5 hash of " + path).print_start() result = run_piped_comma...
0a5747e1094348be042cec165509710661c3be84
3,619,775
from typing import Optional def bool_to_int(bool_value: Optional[bool]) -> Optional[int]: """Cast bool to int value. :param bool_value: some bool value :return: int represenation """ if bool_value is None: return bool_value return int(bool_value)
fde6cda3dc8909638bb315451a09938224f2f306
3,619,776
def create_pool2d(pooling_params, ifm_expr): """Create a relay pooling operation""" assert pooling_params.ifm.layout == "NHWC" params = { "pool_size": (pooling_params.size[0], pooling_params.size[1]), "strides": (pooling_params.strides[0], pooling_params.strides[1]), "padding": [0, 0...
6f163a737993630f7af1264f609a74aee286c4d5
3,619,777
import socket def send_msg(msg: bytes) -> bool: """Send a msg. Returns True on success, False otherwise""" succeed = True try: # 1 second timeout sock = socket.create_connection((c.HOSTNAME, c.PORT), timeout=1) except Exception: return False try: sock.send(msg) ...
b76698cf946b645825272c32771dfac792491840
3,619,778
def check_dwd_observations_parameter_set( parameter_set: DWDObservationParameterSet, resolution: DWDObservationResolution, period: DWDObservationPeriod, ) -> bool: """ Function to check for element (alternative name) and if existing return it Differs from foldername e.g. air_temperature -> tu ...
edc5b9ab3ae6c10db113e6a01d73467bd3d8ff0e
3,619,779
def pobj_ident(l, r): """ Check if value of PObject `l` is the same Python Object as value of PObject `r` """ return mkbool(r.hasvalue and l.value is r.value)
f8c3d7b1867f9869083a41d211971674ed99f703
3,619,780
from typing import Any def arghash(args: Any, kwargs: Any) -> int: """Simple argument hash with kwargs sorted.""" sorted_args = tuple( x if hasattr(x, "__repr__") else x for x in [*args, *sorted(kwargs.items())] ) return hash(sorted_args)
c3e95c63831c958bb2a52cabad9f2ce576a4fed8
3,619,781
from typing import Union from typing import Optional from typing import Sequence def visualize_accuracy_grouped_by_probability(y_test: np.ndarray, labeled_class: Union[str, int], probabilities: np.ndarray, threshold: float = 0...
e9be1be8e5e650b2808fa31db80cfc9fb61e43bd
3,619,782
def run_workflow_stddft(config: DictConfig) -> PromisedObject: """Compute the excited states using simplified TDDFT using `config`.""" # Single Point calculations settings using CP2K mo_paths_hdf5, energy_paths_hdf5 = unpack(calculate_mos(config), 2) # Read structures molecules_au = [change_mol_uni...
ac2f3c6f39765d555530329948aa21719436216c
3,619,784
def build_resnet_fpn_gnbn_lowlevel_cbp10_backbone(cfg, input_shape: ShapeSpec): """ Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. """ bottom_up = build_resnet_gnbn_lowlevel_model_backbone(cfg, input_shape, gra...
81ee7d331ab17bf47f8e252cfebd7a07045c62c9
3,619,786
import pickle def load_db(fname, binp=True, keys=None ): """ Submodule to read the station database from file Parameters ---------- fname : str File name binp : bool Whether or not to use binary input keys : List Default None If a list, then load database a...
5c83b4c4d69ac7f196acc0803593cca87b484499
3,619,788
def _get_pcluster_version_from_stack(stack): """ Get the version of the stack if tagged. :param stack: stack object :return: version or empty string """ return next((tag.get("Value") for tag in stack.get("Tags") if tag.get("Key") == "Version"), "")
86106e52ea6ef8780c8aa8f514e0708dd53fb8e3
3,619,789
import time def condor_object(net): """Initialization of the condor object. The function gets a network in edgelist format encoded in a pandas dataframe. Returns a dictionary with an igraph network, names of the targets and regulators, list of edges, modularity, and vertex memberships. """ t ...
a5b07ee8f8886baff9ae6b25f335d9c42343b3c0
3,619,790
import json def extract(spark, source): """Return an RDD[String].""" rdd = spark.sparkContext.textFile(source) return rdd.map(lambda x: json.loads(x))
fef96d6cae65551a6879396ea699acfd2e4cda4b
3,619,792
def _remove_leading_zeroes_in_field(string): """If blank-separated fields are integer, remove the leading zero.""" split = string.split(" ") for i, field in enumerate(split): if field.isdigit(): split[i] = f"{int(field)}" return " ".join(split)
48ba659b25809f19a0c3ed722d6201ffef73c409
3,619,793
def pstdev(data): """Calculates the population standard deviation.""" #: http://stackoverflow.com/a/27758326 n = len(data) if n < 2: raise ValueError('variance requires at least two data points') ss = _ss(data) pvar = ss/n # the population variance return pvar**0.5
fd67040adf793c5ea4da4125fe007050af40bd1a
3,619,794
def make_sharded_index(index_prefix: str, release_date: Date) -> str: """Make a sharded Elasticsearch index given an index prefix and a date. :param index_prefix: the index prefix. :param release_date: the date. :return: the sharded index. """ return f'{index_prefix}-{release_date.strftime("%Y...
e9e8fa05efcff9868326d8e453f1379f5b134322
3,619,795
def kmp(pattern, text): """Knuth-Morris-Pratt substring matching""" pattern_length = len(pattern) matched, subpattern = 0, [0] * pattern_length for i, glyph in enumerate(pattern): if i: while matched and (pattern[matched] != glyph): matched = subpattern[matched - 1] ...
4f2a30a7a92d2e5890d9c257626c37201b281fec
3,619,797
from datetime import datetime def ssl_valid_time_remaining(hostname): """Get the number of days left in a cert's lifetime.""" expires = ssl_expiry_datetime(hostname) return expires - datetime.datetime.utcnow()
7820dde512fa505b82875fe4a88cf9e5915212c7
3,619,799
def system(cmd): """Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- None : we explicitly do NOT ret...
591c03e6555a271ae3152890888963928bb66d2e
3,619,800
def make_dataset(name, args): """ Creates the dataset with the given name. Parameters ---------- name: the name of the dataset to create. args: hyper-paremeters for the dataset. Returns ------- dataset_fn: a function which creates the specified dataset. """ if name not in _data...
13a06cba585f673a83fcfdbdf1ab32874ac51d65
3,619,801
def create_df(client, candles): """ Создаеv датафрейм для списка свечей :param dict candles: List of candles from API :return: DataFrame with candles """ df = DataFrame([{ 'time': c.time, 'volume': c.volume, 'open': cast_money(client, c.open), 'cl...
4d84cd1c5368586926fcbfd4104aac74c6f807ef
3,619,802
def istext(obj): """ Deprecated. Use:: >>> isinstance(obj, str) after this import: >>> from future.builtins import str """ return isinstance(obj, type(u''))
60f3d751f22ad4d120ce7624dd9a07d2c841e206
3,619,804
def track_to_p_matrix(track, char_map=CHAR_MAP, x_vel_limits=None, y_vel_limits=None, x_accel_limits=None, y_accel_limits=None, max_total_accel=np.inf): """ Converts a map described by a list of strings to P-matrix format for an OpenAI Gym Discrete environment. Maps are specified usin...
68cddbbd0b8bd9bd1b0a0cf33c0d5eb4b9a22a31
3,619,805
def crc16(string, value=0): """CRC-16 poly: p(x) = x**16 + x**15 + x**2 + 1 @param string: Data over which to calculate crc. @param value: Initial CRC value. """ crc16_table = [] for byte in range(256): crc = 0 for _ in range(8): if (byte ^ crc) & 1: ...
e31ddafc6216b682d9cd0ac24a9fb634f1be1fb8
3,619,806
def get_fpn_featureMaps(features,num_filt=256): """ features: list of different maps produced by a backbone **Resnet50** : for resnet50 it contains all the 5 feature maps from each block Return: list of pyramid features """ C1,C2,C3,C4,C5 = features C5d1 = keras.layers.Conv2D(num_filt,(...
3b265bb62163cc075e8aa608bbbf21b654df4b98
3,619,807
import time def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): """Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). S...
bd225cd4ecd5af4a9ee9f29137e46807bf534ee9
3,619,808
def Interface_Static_Standards(*args): """ * Initializes all standard static parameters, which can be used by every function. statics specific of a norm or a function must be defined around it :rtype: void """ return _Interface.Interface_Static_Standards(*args)
85dfea02a10d62203eaf7afe814b7ee25b925cfe
3,619,809
from typing import Sequence from typing import Dict from typing import List def batch_inputs(input_records: Sequence[Dict[K, V]]) -> Dict[K, List[V]]: """Batch inputs from list-of-dicts to dict-of-lists.""" assert input_records, 'Must have non-empty batch!' ret = {} for k in input_records[0]: ret[k] = [r[...
c7e5a13258b131f93d11886f114d49b8804c3bd1
3,619,810
def chunks(seq, size): """Breaks a sequence of bytes into chunks of provided size :param seq: sequence of bytes :param size: chunk size :return: generator that yields tuples of sequence chunk and boolean that indicates if chunk is the last one """ length = len(seq) return ((seq...
25abe8afdb032af0e2b10dbd3c03b369d862813f
3,619,811
def compare( left, right, left_label="left", right_label="right", drop_close=True, **kwargs ): """Compare the data in two IamDataFrames and return a pandas.DataFrame Parameters ---------- left, right : IamDataFrames two :class:`IamDataFrame` instances to be compared left_label, right_la...
0820c606a93d3e12c333d43018f55f53407ff530
3,619,812
def combine_shuffle(parcellation, scale, spatnull, alpha): """ Combines outputs of all simulations into single files for provided inputs Parameters ---------- parcellation : str Name of parcellation to be used scale : str Scale of `parcellation` to be used spatnull : str ...
6e56b3d57e0c14b7a624f406e66c3a902590a2db
3,619,814
def tcycle(iterable, n): """ >>> tcycle([1, 2, 3], 2) (1, 2) >>> tcycle([1, 2, 3], 4) (1, 2, 3, 1) """ return tuple(islice(cycle(iterable), n))
d836316de1dd91770d662aca9fb024c702499317
3,619,815
from typing import List from typing import Callable from typing import Any from typing import Union from typing import Tuple def compute_best_permutation(x: List, y: List, sim: Callable[[Any, Any], Union[bool, int, float]], agg: Ca...
4d0c9a4d1a719c6b67f585e13fb803f8ff81bb6e
3,619,816
import torch def change_box_order(boxes, order): """Change box order between (xmin,ymin,xmax,ymax) and (xcenter,ycenter,width,height). Args: boxes: (tensor) bounding boxes, sized [N,4]. order: (str) either 'xyxy2xywh' or 'xywh2xyxy'. Returns: (tensor) converted bounding boxes, sized [N...
6dd1ef6d2370c79de7ec321ab16592316b7b75da
3,619,817
def GetLidarSimulation(environment,position,orientation): """ This function simulates the operation of the LIDAR by returning a list with the polar coordinates of the location of the obstacles environment -> List with all objects that are in the circuit as well as the edges of the circuit posi...
18b82528945a541411f21f36015c6518cd0e81fd
3,619,818
import ast def For_range(t, x): """Special conversion for ``for name in range(n)``, which detects ``range()`` calls and converts the statement to: .. code:: javascript for (var name = 0, bound = bound; name < bound; name++) { // ... } """ if (isinstance(x.target, ast.Name)...
e1d71e1c76798e7282c67de01dd7ff281ef28f9e
3,619,819
def calculate_G3( n_numbers, neighborsymbols, neighborpositions, G_elements, gamma, zeta, eta, cutoff, cutofffxn, Ri, normalized=True, image_molecule=None, n_indices=None, weighted=False, ): """Calculate G3 symmetry function. These are 3 body or angular i...
41b8e163da879ca9e0339f8ac79f3f3d1abfb6fe
3,619,820
import fractions def decimals(): """Generates instances of decimals.Decimal.""" return ( floats().map(float_to_decimal) | fractions().map( lambda f: Decimal(f.numerator) / f.denominator ) )
b8e376543fc6182e5a9b6434865410f0950d622b
3,619,821
def is_index(obj): """Verifies whether an object is a table index.""" return isinstance(obj, _supported_types().index_types)
e658951433b63e67ddbc4a98439569b1fb5b98fc
3,619,822
def stack_controls(controls: list[dict], key: str = "tau"): """ Stack the controls in one vector Parameters ---------- controls : list[dict] List of dictionaries containing the controls key : str Key of the controls to stack such as "tau" or "qddot" """ the_tuple = (c[ke...
8936bfbb1e4074cc79157fbdffaeb9e75de93f3a
3,619,823
def secondYAxis(requestContext, seriesList): """ Graph the series on the secondary Y axis. """ for series in seriesList: series.options['secondYAxis'] = True series.name= 'secondYAxis(%s)' % series.name return seriesList
d1c34f16da1f2142021c845afffb63b595e2ce69
3,619,824
def _next_incompatible_version(version): """ Find the next non-compatible version. This is for use with the ~= compatible syntax. It will provide the first version that this version must be less than in order to be compatible. :param str version: PEP 440 compliant version number :return: T...
7a9bdddf27cdd06e975236b0e7a64ae38d08bc98
3,619,825
def SNR_tot(G, BP, RP, J, H, K, lum, mass, teff, rad, numax, s=1., deltaT=1550, Amax_sun=2.5, obs='kepler-sc', D=1): """ predicted S/N for a given set of parameters INPUT: mag - relevant magnitude e.g. V or Kp for kepler... lum - luminosity in Lsun mass - stellar mass in Msun ...
14c1f2d1b612fa5a4c1a3b820b14d7d49cab563e
3,619,826
def checkFormat(DATAFIL): """ check the file format """ # Open file, read first 4 bytes as string f = open(DATAFIL, 'rb') dataBytes = np.fromfile(f, dtype=np.uint8, count=4) data = "".join(map(chr, dataBytes)) f.close() # If string matches a particular format, return format if d...
8e82a9f3a62092dbe75d7d948756eecc026b4b45
3,619,827
from datetime import datetime import csv def parse_csv(csv_path, ftype='csv', dt_col="date_time", dt_format="%Y%m%d %H:%M:%S", dni_col='DNI', dhi_col='DHI', stime=None, etime=None): """Parse a csv file containing direct normal and diffuse horizontal data, ignoring NULL and zero...
e29c7dbbb71b0353ceec0522ecab382f429d3c6a
3,619,828
import logging def CreateChrootSnapshot(snapshot_name, chroot_vg, chroot_lv): """Create a snapshot for the specified chroot VG/LV. Args: snapshot_name: The name of the new snapshot. chroot_vg: The name of the VG containing the origin LV. chroot_lv: The name of the origin LV. Returns: True if t...
ef804e01da6143b2ff4393a27a6db16c66fc5ff4
3,619,830
import typing def decode_u256(as_bytes: typing.List[int]) -> int: """Decodes an unsigned 256 bit integer. """ size = as_bytes[0] if size <= NUMERIC_CONSTRAINTS[CLTypeKey.U8].LENGTH: return decode_u8(as_bytes[1:]) elif size <= NUMERIC_CONSTRAINTS[CLTypeKey.U32].LENGTH: return d...
0fd8e9a47a805d9d56c6d019c470e22a06e0c606
3,619,831
def image_code(): """ 图片验证码的实现逻辑 1. 获取参数 图片验证码的随机值 ! 切记! 一定要判断 2. 生成图片验证码 3. 将图片文字和随机值保存到redis中 4. 将图片验证码 返回 :return: """ image_code_id = request.args.get("imageCodeId", None) # 判断参数是否有值 if not image_code_id: abort(403) # 生成图片验证码 name, text, image = capt...
cb154182071efd367d1229e058cf90166b7bea44
3,619,833
from typing import Union from pathlib import Path from typing import Optional def clone_renku_repository( url: str, path: Union[Path, str], gitlab_token=None, deployment_hostname=None, depth: Optional[int] = None, install_githooks=False, install_lfs=True, skip_smudge=True, recursiv...
1fbc1941b670caab64619705c666d636f0f6bcf1
3,619,834
def display_content(value): """This callback is used on the User Guide page and returns the selected User Guide when a user selects a certain tab. User Guides can be added to HIVE in the userguide.py page. """ return userguide.user_guide(value)
f47dd22f395b8b249d2d2bfc1d14a09f6004325b
3,619,836
def adjust_anomaly_scores(scores, dataset, is_train, lookback): """ Method for MSL and SMAP where channels have been concatenated as part of the preprocessing :param scores: anomaly_scores :param dataset: name of dataset :param is_train: if scores is from train set :param lookback: lookback (win...
2f6adcdcae841573b362f1629138fdc70a568a24
3,619,837
import mpmath def sf(k, nc, ntotal, ngood, nsample): """ Survival function of Fisher's noncentral hypergeometric distribution. """ _hg._validate(ntotal, ngood, nsample) sup, p = support(nc, ntotal, ngood, nsample) if k < sup[0]: return mpmath.mp.one elif k >= sup[-1]: retur...
4b4915b3bc2a9201bb66fca3e630cf59cd9afc8e
3,619,838
def part_2_solution(graph, search_key): """ keeps a persistant counter that is recursively passed into a helper function for ever depth of the helper function, the branch product gets updated, when a recursive function exits it updates the counter with the product of counts for each sub-bag the co...
16ac48370de6d94397747b6b16791e0615f390aa
3,619,839
def get_func_qty(*args): """get_func_qty() -> size_t""" return _idaapi.get_func_qty(*args)
affa7952d604fd20674cadbe76cd9f55db669c14
3,619,841
def is_model_quantized(sym_model): """Checks whether the model is quantized. Args: sym_model (tuple): symbol model (symnet, args, auxs). Returns: boolean: True if model is quantized, else False. """ assert isinstance(sym_model, tuple) and isinstance(sym_model[0], mx....
32e8fd62bbc3280c0edd158194e8e7b2ffee53bf
3,619,842
def evaluate(bounds, func): """ Evaluates simpsons rules on an array of values and a function pointer. .. math:: \int_{a}^{b} = \sum_i ... Parameters ---------- bounds: array_like An array with a dimension of two that contains the starting and ending points for the int...
af5102d37c1943420a0ff3fff980342ee8c9dad9
3,619,843
def process_image(image, target_shape): # downsampling to desired shape """Given an image, process it (downsample if needed) and return a numpy array.""" h, w, c = target_shape image = load_img(image, target_size=(h, w)) # Load the image. Downsampling included! e.g. to (32,32,3) img_arr = img_to_array(...
968daaf8da198fc4ce129ea07c57c84942dc86ab
3,619,844
import hashlib def get_dataset_id(settings): """ Creates and returns an unique ID (for practical purposes), given the data parameters. The main use of this ID is to make sure we are using the correct data source, and that the data parameters weren't changed halfway through the simulation sequence. """...
a696f0f85c8ee9c3cab975838db520cc061dfaf4
3,619,845
def get_sampler_diags(fit): """Returns useful sampler diagnostics for a particular MCMC fit with pystan""" rhat=fit.summary()['summary'][:,-1] rhat_worst=rhat[np.abs(1-rhat)==max(np.abs(1-rhat))][0] n_eff_int_site=int(fit.summary()['summary'][0,-2]) return rhat_worst,n_eff_int_site
acee6147024ae32116e8b905eae18d8e47125148
3,619,846
def get_category(url=None, category='nieruchomosci', transaction_type='wszystkie', voivodeship=None, city=None, street=None, filters=None): """ Parses available offer urls from given category search page :param url: Url to search web page :param category: Type of property of interest (Mies...
60aa51056bb209de8b777a7977504ab04847b6a2
3,619,847
def wmt_preprocess(dataset, training, max_length=-1, max_eval_length=-1): """Preprocessing for LM1B: filter out targets exceeding maximum length.""" def train_right_length(example, target): l = tf.maximum(tf.shape(example["inputs"])[0], tf.shape(target)[0]) return tf.less(l, max_length + 1) def eval_rig...
870d1c1a7b6ee8e2a9c424884558355d4164a6d6
3,619,848
import torch def instance_masks_to_semseg_mask(instance_masks, category_labels): """ Converts a tensor containing instance masks to a semantic segmentation mask. :param instance_masks: tensor(N, T, H, W) (N = number of instances) :param category_labels: tensor(N) containing semantic category label fo...
127c9b9ff3d1044b1c5e1e8650ed493f8a4bc6de
3,619,849