content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_module(obs_space: Space, action_space: Space, config: dict) -> nn.Module: """Retrieve and construct module of given name. Args: obs_space: Observation space action_space: Action space config: Configurations for module construction and initialization """ type_ = config.po...
1554ef3641a1b10468df770c4a0407800ff8547c
36,532
def _replace_event_values_arr( timearr: NDArray[float], old_value: int, new_value: int ) -> NDArray[int]: """Replace the values 'old_value' with 'new_value' for the array.""" timearr[np.where(timearr == old_value)] = new_value return timearr
28a23d989798fa6b8dde55c64c0d52df1812f727
36,534
def validate_api_host_url(url): """ Validate SolveBio API host url. Valid urls must not be empty and must contain either HTTP or HTTPS scheme. """ if not url: raise SolveError('No SolveBio API host is set') # Default to https if no scheme is set if '://' not in url: url...
92f8bf36c8b39805c6cc76608f49c9a85efb2b6d
36,535
def search_permission_filter(): """Filter list of results.""" # Send empty query for admins if Permission(superuser_access).allows(g.identity): return Q() provides = get_user_provides() # Filter for public records public = Q('missing', field='_access.read') # Filter for restricted ...
9f7219b0cacbb3d27bffcd61e76f1e487f359692
36,536
def check_depth_submission(path): """Checks if all files required for the submission exist and are in the right format.""" ready_for_submission = True ready_for_submission = ready_for_submission and _check_frames(_get_test_frame_paths('depth', path, '.pfm')) return ready_for_submission
80e46c17d531f60976573db775a3cde70a3d01df
36,537
def qual2fastq(quals): """ Convert a list of quality scores to a single fastq line :param quals: A list of quality scores :type quals: list :return: A fastq quality string :rtype: str """ quality = [chr(q + 33) for q in quals] return "".join(quality)
e32f52da5a9ada3fdf8b1789c6e3982044f775f7
36,538
def generate_honeycomb_coordinates(n_x, n_y, scaling=1.0): """ Generate coordinates from a honeycomb mesh which can be used to set up a cell population. Parameters ---------- n_x: int number of columns n_y: int number of rows scaling: float distance between the c...
0207826e53714bcd780c28799d0879d53b5b0607
36,539
import pathlib def exists(path: str) -> bool: """Checks if path exists e.g j.sals.fs.exists("/home/rafy/testing_make_dir/test1") -> True j.sals.fs.exists("/home/rafy/testing_make_dir/fasdljd") -> False Args: path (str): path to check for existence Returns: bool: Tru...
a3b3717c947656042d3ddcf9e1107d3f6ec9c06d
36,540
def load_token(token): """ decrypt token and load User """ max_age = app.config['REMEMBER_COOKIE_DURATION'].total_seconds() data = login_serializer.loads(token, max_age=max_age) u = model.Users.query.filter_by(email=data[0]).first() if u and data[1] == u.password: return u retu...
afb1d1471c1d3d28e18fef575194fba6b4ede974
36,541
import this def heSHjuBBFVLp(): """Let notation.""" return Injector.let(bar=(this << 2).foo)
3ada0c74b4c3aa360ebaa15f00457abc4ed89e64
36,542
def _create_cql_update_query(key_space: str, table_name: str, set_columns_value_dict: dict, primary_key_values: dict) -> str: """ This function will create an update CQL query""" cql_update = "UPDATE " + key_space + "." + table_name + " SET " for key...
b133feef14daefe7f5cc82936c2399bad3139672
36,543
def apply_psd(signal_t, psd, sampling_rate=4096, apply_butter=True): """ Take a signal in the time domain, and a precalculated Power Spectral Density, and color the signal according to the given PSD. Args: signal_t: A signal in time domain (i.e. a 1D numpy array) psd: A Power Spectral D...
7289ff3135b94197dd9a97cfc44c07700eb553a4
36,544
def do_zoom_image_job(port_input_name: str, zoom_factor: float, do_interpolation: bool = True, port_output_name: str = None, level: PYRAMID_LEVEL = PYRAMID_LEVEL.LEVEL_0, wave_offset: int = 0, is_rgb: bool = False) -> str: """ Function for zoomin...
67d5475268a494459d4317799b07a5d969491eee
36,545
def update_raid_group_resync_speed(session, raid_id, minimum, maximum, return_type=None, **kwargs): """ Updates the speed at which a RAID group will rebuild using the minimum and maximum arguments. :type session: zadarapy.session.Session :param session: A valid za...
e40d387378e4a0499b2180980ff679b0df82dd46
36,546
def extract_file_number(file_name): """ Extract the file number from a file name """ file_name = str(file_name) dot_contents = file_name.split('.') hyp_contents = dot_contents[0].split('-') base_name = hyp_contents[len(hyp_contents) - 1] return int(base_name[:-1])
0b29ba7e75ddfcdc31832641d51f5f0a507021b0
36,549
from re import S def solve_rational_inequalities(eqs): """ Solve a system of rational inequalities with rational coefficients. Examples ======== >>> solve_rational_inequalities([[((Poly(-x + 1), Poly(1, x)), '>='), ... ((Poly(-x + 1), Poly(1, x)), '<=')]]) {...
5e471fc24fc272e33b7ba777694eae038c7874df
36,550
import torch def BHV_diffeo( ind_current_topo, dictionnary_topology_comparison, mask_topo_comparison, mask_topo, mask_segments, singular_template, singular_connections, n_leaves, template, template_connections, target, target_connections, ...
9f13b5a8405895ab66450989f2762029d050323b
36,551
def add_address(x, y): """Returns a string representation of the sum of the two parameters. x is a hex string address that can be converted to an int. y is an int. """ return "{0:08X}".format(int(x, 16) + y)
3e6fef3d5de0216c68c980b24d9f1ab05bc0a043
36,552
def inv_linear_DisPrinc_sparse( Tn=None, TTn=None, Tyn=None, R=None, yn=None, sol0=None, nchan=None, mu0=None, precond=None, verb=None, verb2head=None, # specific chi2n_tol=None, chi2n_obj=None, maxiter=None, tol=None, **kwdargs, ): """ Discrep...
64be8690491f89c43c945ec8963ef529371065b8
36,553
import re def replaceRoadWithRd(a_string): """assumes a_string is a string returns a string, with "Rd." where a_string has "Road" """ pattern = "[Rr]oad" replacement = "Rd." result = re.sub(pattern, replacement, a_string) return result
08cafdc84c61fc4131f923bf65f271b1d08be0c9
36,555
def get(columns=None): """Get or create MetaData singleton.""" if columns is None: columns = _DEFAULT_COLUMNS global _METADATA if not _METADATA: _METADATA = MetaData(columns) return _METADATA
ef37b70a7f870543b5e19ed290e2fe3cbb26b015
36,556
def read_data(report_name: str): """Читает исходные данные по стоимости портфеля из файла""" data = pd.read_excel(REPORTS_DATA_PATH / f'{report_name}.xlsx', sheet_name=SHEET_NAME, header=0, index_col=0, converter...
714513b7c9538cbf7823fb1099420320dcd884a3
36,557
def extract_fcp_data(raw_data, status): """ extract data from smcli System_WWPN_Query output. Input: raw data returned from smcli Output: data extracted would be like: 'status:Free \n fcp_dev_no:1D2F\n physical_wwpn:C05076E9928051D1\n channel_path_id:8B\n npiv_wwp...
bbe9de1f075fa68a4130c44afea9d388b1a678d5
36,558
def prepare_design_symmetry(D: np.ndarray) -> np.ndarray: """Add to the design matrix strip simmetric to the one in the input Args ---- D: np.ndarray The design matrix as it comes from build_Design_Matrix Returns ------- New design matrix with appended the simmetric angles ...
2e5f1d9c01cf847f19985d51f04d0bf9e84821f7
36,559
def generate_output_html(htmlfile): """Load HTML template and add current date, return result""" try: with open(htmlfile) as f: html = f.read().format(date_string) return html except Exception as ex: logger.error('Exception occured while loading template {}. Details: ...
e7794d1d132858b45fba326d983b31d0e7c366e9
36,560
from typing import Union from typing import Dict def check_existence_and_date_s3(query_hash: Union[int, str]) -> Dict[str, str]: """Check if a query hash has corresponding result and query json on S3 Parameters ---------- query_hash : The query hash to check Returns ------- : ...
1d25d4869aa874b85a85dd376f8ff59e07712375
36,561
def verifying_key_from_hex(key: bytes): """Load the VerifyingKey from a compressed or uncompressed hex public key. """ id_byte = key[0] if not isinstance(id_byte, int): id_byte = ord(id_byte) if id_byte == 4: # Uncompressed public point # 1B ID + 32B x coord + 32B y coord = 6...
c87efcee39bd92a0988aeb85b3b055d8d6a951c7
36,562
def get_graph(): """Creates dictionary {node: {child1, child2, ..},..} for current TensorFlow graph. Result is compatible with networkx/toposort""" ops = tf.get_default_graph().get_operations() return {op: children(op) for op in ops}
a0b912395a550bf2f2b2bf929f7ab90b97a3ba98
36,563
def find_coord(find_coords, search_coords, tol=1.e-6): """ {TEST} Find the index for the coordinate in search_coords that matches the coordinate find_coords. :param find_coords: Coordinates for the point to find :type find_coords: tuple[ float ] :param search_coords: Coordinate lists ...
94fe9cee4ac639337f0a9b4649ac5893133b06f9
36,564
def nonOverlappingMinima(minDists, m, fromSeq=None): """ Returns the indices i such that (minDist[i] <= minDists[j] or fromSeq[i] != fromSeq[j]) for all j in [i, i + m - 1]. If fromSeq is not provided, the latter test always fails (i.e., both dists are assumed to be from the same sequence, and thus able to overlap...
5362dbdfa42b8d0aedb7b780720f793baae7ab4c
36,565
def draw_contour_(contour_img, contour, color, gradient_colors=("red", "blue"), min_size=10, filled=True, compute_mask=False): """ Draw a contour as optionally fill it with color. Differs from draw_contour() i...
73f4bc88699d9d090972a474f8826eb47e5a9cc8
36,566
def list_to_include_array(data_list): """Convert python list to ble_gattc_include_array.""" data_array = _populate_array(data_list, driver.ble_gattc_include_array) return data_array
f84aea79d33d9de01047841891a67570ed161da7
36,568
def check_for_valid_numerical_encoding_of_labels(labels): """ Checks whether the labels are numerical labels satisfying the following requirements: 1. each label is an integer greater or equal to zero 2. the smallest label is zero The labels encoded by applying "sklearn.preprocessing.La...
a4e356b3d8680b330f6c6b9aff1082e95b39ec72
36,569
import torch def video_pack_sequences(in_batch): """ Pad the variable-length input sequences to fixed length :param in_batch: the original input batch of sequences generated by pytorch DataLoader :return: out_batch (list): the padded batch of sequences """ # Get the number of return va...
983b86cfb867268ca0759b4cdf29052153d97785
36,570
from operator import sub def generate_nologin_hash(public_string): """Generate hash for users who are not logged in""" hex_hash = sha256(settings.EMAIL_SECRET_KEY + public_string).hexdigest() # Decode the hex hash into base64, reducing the length of the code b64_hash = hex_hash.decode('hex').encode("...
7781848e151d1054d8338bef1728863c02a53b3c
36,571
def compute_v_dot_upper_bound(dV, mean, variance=None, beta=2.): """ Compute the safe set Parameters ---------- dV: np.array The derivatives of the Lyapunov function at grid points mean: np.array mean of the dynamics (including prior dynamics as mean) variance: np.array ...
927cec0dda57b55da9e30a1cd21e1c5ef8f7fa84
36,572
import json def decode_resource_id_options(request): """ Extract resource ID options from a HTTP request, making sure the keys have the same names as the ResourceIdentifier object's fields. """ return { # Resource ID 'resource_id': request['id'], 'target_platforms': json.dumps(requ...
97f61b5c1ffb82cb9f29caebb9a85d42348fbfa7
36,576
import json def load_data(data): """ Wrapper to load json data, to be compatible with Python3. Returns: JSON data Keyword arguments: data: might be bytes or str """ if type(data) == bytes: return json.loads(data.decode("utf-8")) else: return json.loads(data)
c33c661c2a42d162d06c3e17487e072908fd0bf4
36,578
import itertools def Pauli_strings(num_qubits): """Returns the matrix representation of Pauli strings of size=num_qubits. e.g., for num_qubits=2, it returns the matrix representations of ['II','IX','IY','IZ,'XI','YI',...]""" pauli_labels = ['I', 'X', 'Y', 'Z'] Pauli_strings_matrices = [Pauli(''.join(p...
256fa607695c067c4d4c13543a5c7010e2c0b212
36,579
def factor_rank_autocorrelation(factor_data, period=1): """ Computes autocorrelation of mean factor ranks in specified time spans. We must compare period to period factor ranks rather than factor values to account for systematic shifts in the factor values of all names or names within a group. This ...
d1a527313aa44f0fbd0b9abe23581934c163cd1f
36,580
def indices_for(df, nprocs): """ group rows in dataframe and assign each group to each process Args: df: Pandas dataframe object nprocs: number of processes used Returns: indeces grouped to each process """ N = df.shape[0] L = int(N / nprocs) indices...
c68408e6fcf70b885ca86fb80f8c31b0bd07e334
36,581
def _dynamic_range(fig, range_padding=0.05, range_padding_units='percent'): """Automatically rescales figure axes range when source data changes.""" fig.x_range.range_padding = range_padding fig.x_range.range_padding_units = range_padding_units fig.y_range.range_padding = range_padding fig.y_range.r...
e3c82605ab20ad6ab3c6f2a6e6d32479a9012ed2
36,582
def norm(x): """ This function takes an array and makes it strictly superior to zero. This is NOT a normalizing function, as it doesn't scale each value relatively to the others. :param x: Array to make superior to zero. :return: Resulting array. """ return np.log(np.exp(x + 1))
630c77de869d36d02b987fa6d3c755501d162cd5
36,583
def _match_expr(parent, expr): """Match expressions to rewrite `A.select(A < 5)` into select expression The argument must match the parent, so this _won't_ be rewritten: `A.select(B < 5)` """ args = expr.args op = expr.op if ( expr.method_name == "apply" and len(args) == 2 ...
8eaaff2b5edf7c36ea500479bee70c7d67cff412
36,584
def generate_new_api_key(user_id): """ Generate a new API key for the user. :param user_id: User ID for which to generate a new API key :return: User object for that user ID with a modified API key :raises UserDoesNotExistException: If no user exists with the given user_id """ user = get_us...
e374fbc5f7da258e67ec2101741230e34b6b3eb9
36,585
def account_reset(): """Handler for account reset.""" return account_handler("account_reset")
c395bd8fa18080ddc4d9aaf8183d899aee6dfbd3
36,586
def _get_validated_config_mapping(name, config_schema, config_fn): """Config mapping must set composite config_schema and config_fn or neither.""" if config_fn is None and config_schema is None: return None elif config_fn is not None and config_schema is not None: return ConfigMapping(confi...
cddab5a70c64d1985ce65e56887138cf9a9a0aef
36,587
def find_ops(optype): """Find ops of a given type in graphdef or a graph. Args: optype: operation type (e.g. Conv2D) Returns: List of operations. """ gd = tf.get_default_graph() return [var for var in gd.get_operations() if var.type == optype]
03d1902adc0872170b618257da488c4ec05d276d
36,588
def continuous_ob(orderbooks): """ Creates a continuous orderbook timeseries data, for all orderbooks included as input. i.e. all timestamps that one orderbook has and the other dont, in the latter repeates the information of the former, with this, the output will deliver two historical orderbooks with ...
03a5124a58f51625b1a63535f8b7ca3d06058aa7
36,590
from util import PriorityQueue # i use PriorityQueue to store the frontier def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE ***" frontier = PriorityQueue() # initialize frontier explored = s...
99ff121f4415f7e730963b73ee5269f310f8ce4d
36,591
def split_irregular_date_list(date_list): """ Takes a list of dates and groups it into blocks of continuous dates. It returns the begin and end of those blocks eg. A list with continuous dates from januari to march and september to october will be split into two lists Parameters ---------- ...
d246e25dacb4d1c7e60f40cbafb653a90d4556d3
36,593
import tqdm import torch def validate(args, fid_stat, gen_net: nn.Module, writer_dict=None): """ Compute both IS and FID (torch). :param args: :param fid_stat: :param gen_net: :param writer_dict: :return: """ # eval mode gen_net = gen_net.eval() eval_iter = args.num_eval_i...
ceadaca144a937eadf7b47fd69ae9b1e65700c14
36,594
def transform_observation(attribute, data): """ place to hook any transforms on te data """ output = data if (attribute == 'observation_time'): output = data[16:] return output
875d35a6c66cf57fe7ac4995f913b8dbe70e63f3
36,595
import json def batch_handler(repo, request): """Handle batch requests.""" req = {} try: req = json.loads(request) except json.JSONDecodeError: return create_response(status_code=400) operation = req['operation'] objects = req['objects'] res_objects = [] for obj in ob...
5a159645edcda539f3a56f53ffb5f3273b7cea49
36,596
def cos_angular_separation_tf(y_true, y_pred): """ Compute the angular separation in radians between two pointing direction given with lat-long Parameters ---------- lat1: 1d `numpy.ndarray` , latitude of the first pointing direction long1: 1d `numpy.ndarray` longitude of the first pointing ...
2ff53483b94f07d7c34e096bf5c2757813aa152a
36,597
def all_stocks(): """ #查询当前所有正常上市交易的股票列表 :return: """ data = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,area,industry,list_date') # d = data["symbol"].values # random.shuffle(d) return data["symbol"].values
0f8ef4b09ea908b0012b6605feaf9c97287e069c
36,598
def get_dependent_databases(demand_dict): """Demand can be activitiy ids or tuple keys.""" db_labels = [ x[0] if isinstance(x, tuple) else get_activity(x)["database"] for x in demand_dict ] return set.union(*[Database(label).find_graph_dependents() for label in db_labels])
37edfaa699bc2d1deefd93dc90961ac76b0470d5
36,599
from typing import Sequence def build_action_observations( observations: Sequence[data.Observation] ) -> Sequence[data.ActionObservation]: """Given observations, creates the actions associated with them. Args: observations: a sequence of Observation objects capturing a PanoContext, a heading, and t...
cec2c5007c7192e778ecf3c6edd5ef2aef781850
36,600
def handle_write_config_request(config_request): """Set piaware-config setting Expected config_request format: { "request": piaware_config_write "request_payload" : {"rtlsdr-gain": 20, "wireless-network": "no"} } request_payload must be a dictionary of key/v...
8e91fdafac073813e4365eb1f535375bfdb4bf8a
36,601
import numpy def nanallclose(x, y, rtol=1.0e-5, atol=1.0e-8): """Numpy allclose function which allows NaN Args: * x, y: Either scalars or numpy arrays Returns: * True or False Note: Returns True if all non-nan elements pass. """ xn = numpy.isnan(x) yn = numpy.is...
053fdc260d215304f0e913a468775dd4ce86dba9
36,602
import re def get_current_data(cfg): """Reads the output file to see what are the contents of the arrays and the version control string Returns a dictionary with: 'etag' -- Etag of the source file used to render the file. As stored in the version control string 'date' -- Date of the source file used to render t...
7b17b6410b2f38c9fc21cd4904b43673dc227014
36,603
def vgg13_bn(pretrained=False, requires_grad=False, **kwargs): """VGG 13-layer model (configuration "B") with batch normalization Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ if pretrained: kwargs['init_weights'] = False model = VGG(make_layers(cfg['...
38f4e2ca715b310c914c7753ac90b66c5c305916
36,604
def get_shape_label(): """Get shape of the labels in Thyroid dataset""" return (None,)
cc7bd48de40de185f39450e360846adc81383aca
36,605
import random def pick_random_question(df_questions, topic_id): """Randomly pick a question for a given topic Random choice uses 1/box as weight Parameters ---------- df_questions: DataFrame DataFrame containing questions columns = ['ID_question', 'ID_topic', 'label', 'link', 'bo...
036997a7b80dda05fcb4f1d7a029567b257e35c1
36,606
def CTDensityPixel_getGray(): """CTDensityPixel_getGray() -> vpl::img::tDensityPixel""" return _Core.CTDensityPixel_getGray()
9b61f68a6231ef2c2685c5755653eeb8b37e65ab
36,607
import math def bfm2Mesh(bfm_info, image_shape=default_init_image_shape): """ generate mesh data from 3DMM (bfm2009) parameters :param bfm_info: :param image_shape: :return: mesh data """ [image_h, image_w, channel] = image_shape pose_para = bfm_info['Pose_Para'].T.astype(np.float32) ...
2683ec2f532ca8e837797bd09a586e84716b953e
36,608
def _merge_css_item(item): """Transform argument into a list with a single string value.""" if isinstance(item, (list, tuple)): return _merge_css_list(*item) item = f"{item}" if item else "" return [item]
dd844fa6ede8b4515e02ab3498242b7a03443af2
36,610
def get_iscsi_auth_groups(client): """Display current authentication group configuration. Returns: List of current authentication group configuration. """ return client.call('get_iscsi_auth_groups')
4a31f6c1f1ea4fa543ee731d54e699cdd108e512
36,611
def _filter_returned_ops(fn): """Filtering out any ops returned by function. Args: fn: a function Returns: A tuple of ( Wrapped function that returns `None` in place of any ops, dict that maps the index in the flat output structure to the returned op ) """ returned_ops = {} def wr...
b4e3cdb09746dad6ffccd547c3c94ce5b779dbcb
36,614
def subclass_of(*args): """ This type validation function can be used in two modes: * providing two arguments (c, ref_type), it returns `True` if issubclass(c, ref_type) and raises a IsWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * provid...
7f9e8d224756d5da0eb775cb6861788d6c558fc5
36,615
from typing import Tuple from typing import List from typing import Dict from typing import Any def info() -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: """ Get input and output schemas :return: OpenAPI specifications. Each specification is assigned as (input / output) """ input_sample = ...
282f60cacac69865736c58712c4bfbdb2f5e2c24
36,616
def region_growing_lab_hsv(I, max_dist, min_pixels=1, smoothing=0): """Performs region growing on an color image in HSV space. Parameters ---------- I : ndarray of float32 3D array representing the image max_dist : float maximum hsv distance to add a neighbou...
f595b92a71ac1f15c0bf5683ed0c49ae3b9b8035
36,617
def wolf_mass(sigma, Re): """ Wolf mass estimator from Wolf+ 2010 Args: sigma : 1D line of sight velocity dispersion in km/s Re : 2D radius enclosing half the stellar mass in pc Returns: estimate of the dynamical mass within the half light radius in Msun ...
7b5258858e932c0b15eaf45a32d08dcf655f1c24
36,618
async def delete_pokemon(id: int): """ ## Deletes a Pokemon by ID. Path Parameters --------------- Pokemon ID. Body Parameters --------------- None Returns ------- None """ if not await PokemonRepository.exists(id=id): # Non-existent Pokemon, ...
5d0917fbae0bcfeb4c567dd0d15979c02637fb38
36,619
import requests import itertools def anagrams_in_list(word, list_of_words): """Given a word (str) and list of words (list or tuple, a list is returned with the valid anagrams of the word in the list of words Args: - word (str): The word that you want to test - list_of_words (list or tuple...
3b8621c81bae1fb274cd740113c844ecfeaa83ce
36,620
def oavol(x, y, z, v, xx, yy, zz, pmap=None, weight=10, nx=2, ny=2, verbose=False): """ Objective analysis interpolation for 3D fields Parameters ---------- x: array [2-D] x-values of source data y: array [2-D] y-values of source data z: array [3-D] z-value...
a1a8d1e0e474fea0a99bd4173c0ba2aa892a4773
36,622
from typing import List from typing import Optional def create_study( name: str, description: str, run_ids: List[int], alias: Optional[str], benchmark_suite: Optional[int], ) -> OpenMLStudy: """ Creates an OpenML study (collection of data, tasks, flows, setups and run), where the runs ...
bfb3f8ca2650b59754dba8f72077543d91167050
36,623
def nats_to_params(nat1, nat2, nat3, nat4): """ natural parameters to distribution parameters """ alpha = nat1 + (1./2) nu = -2 * nat4 mu = nat3 / nu beta = - nat2 - (nu * (mu**2) / 2) return alpha, beta, mu, nu
56fba0a886d35948edf570c6eb379f6e0175b589
36,624
def depth_type_order(order): """Create a function which constrains paragraphs depths to a particular type sequence. For example, we know a priori what regtext and interpretation markers' order should be. Adding this constrain speeds up solution finding.""" order = list(order) # defensive copy ...
ed22f589f05df52c736c29ccbaef22c14eb24b6b
36,625
from typing import Dict def euclidean(a: Dict, b: Dict)->float: """Return the euclidean distance beetween the given dictionaries. Parameters ---------------------------- a: Dict, First dictionary to consider. b: Dict, Second dictionary to consider. Returns ---------------...
88311a84606ede224437b87a128b76d0da458474
36,626
def get_system_category(): """获取文档分类""" systems = ComponentSystem.objects.all() doc_category = {} for system in systems: if not system.has_display_doc: continue system_doc_category = system.doc_category doc_category.setdefault(system_doc_category.id, { 'na...
712669eaa4b044f9fd62e2589a1462678aabbc2f
36,627
from typing import Iterable def _serialize_graph(ops): """ Serializes a graph and returns the actual protobuf python object (rather than serialized byte string as done by `serialize_graph`). """ assert isinstance(ops, Iterable), "Ops passed into `serialize_graph` must be an iterable" ops = Op....
65458fe18fff382c90aa9a1bb97f3d654ccac766
36,628
def single_cell_variables(model_name, dat, let): """ Single cell variable of model_name. 1: head, 2:temp, 3:conc, 4:kz, 5:lz, 6:por (inside mem) 11: head, 12:temp, 13:conc, 14:kz, 15:lz, 16:por (not inside mem) """ output_path = rm.make_output_dirs(model_name, dat, let)[0] enkf_inpu...
711389851f58dcce652d1bb891ca8cd48b805a15
36,629
import sqlite3 def add_signature(db, df): """Adds `signature` from database `db` to dataframe `df`.""" events = df["event_no"] with sqlite3.connect(db) as con: query = ( "select event_no, pid, interaction_type from truth where event_no in %s" % str(tuple(events)) ) ...
5ff85591bf03393cbc428abde40242e6ca3c39f0
36,630
import re def getLLVMVersion(llvmProgram): """executes the program with --version and extracts the LLVM version string""" versionString = getVersion(llvmProgram) printLLVMVersion = re.search(r'(clang |LLVM )?(version )?((\d)\.\d)(\.\d)?', versionString, re.IGNORECASE) if printLLVMVersion is None: ...
2facaaf70824febdfb6a79956138963d0f61b6ce
36,631
def lambert(disk): """Converts coordinates on the disk to spherical coordinates, using the Lambert azimuthal equal-area projection. Args: disk: Array of shape [..., 2] representing points on the disk. Returns: phi, theta: Spherical coordinates >>> phi, theta = lambert(_TEST_DISK_R...
6e6461e06fe0092ea9806fba1874a5153d3115cb
36,633
def mandel_geom(params, x, etc = []): """ This function computes a transit shape using equations provided by Mandel & Agol (2002). Parameters ---------- midpt: Center of eclipse width: Eclipse duration from contacts 1 to 4 rp_rs: Planet-star radius ratio b: Impact parameter flux...
62c2b41435600381200af66b9465b054c1a1d0f9
36,634
def from_columns(mapping, fp): """ Write columns to the open file opbject ``fp`` in XPT-format. The mapping should be of column names to equal-length sequences. Column labels are restricted to 40 characters. The XPT format also requires a separate column "name" that is restricted to 8 characte...
55b5436bfbb99ddaa90b413171111748d1a799b6
36,636
def list_random_circuits_onelen(opLabels, length, count, seed=None): """ Create a list of random operation sequences of a given length. Parameters ---------- opLabels : tuple tuple of operation labels to include in operation sequences. length : int the operation sequence length...
6f3a849a54d201dcd39c743b997c9409b5c834da
36,638
def get_number_of_pictures(directions,cutOff,referenceAtom): """ Finding the amount of copies of the original SuperCell .---------------------------. / \ \ / \ \ / \ ...
e175e12329707312cd3aa78cb027e70b728756fc
36,640
def _create_extension_feed_items(client, customer_id, campaign_resource_name): """Helper method that creates extension feed items. Args: client: a GoogleAdsClient instance. customer_id: a str Google Ads customer ID, that the extension feed items will be created for. campaign...
54eb2ff33e8bea07c8dad0a91201d63484bd9924
36,641
def rgb2hsv(img): """ Use matplotlib to convert rgb to hsv (TA allowed) """ return (rgb_to_hsv(img.astype(np.float32) / 255.) * 255).astype(np.uint8)
2afaefd68fbc68c1c36e8a0000fca999d7f30e83
36,642
def get_territory_options_formatted(): """ Formats list of territory options per Dash dropdown standards. Example of returned data structure: {'country': [{'label': 'Algeria', 'value': 'Algeria'}, {'label': 'Angola', 'value': 'Angola'}], 'state': [{'label': 'Alberta, Canada', 'value': 'Alberta, Canada'}...
5359d6bb6581772244a66c7a7568275589145f48
36,643
def _get_resources(rtype='resources'): """ resource types from state summary include: resources, used_resources offered_resources, reserved_resources, unreserved_resources The default is resources. :param rtype: the type of resources to return :type rtype: str :param role: the name of the role...
04746e33685d503adb9f0a3527a7bc203ab639b3
36,644
def feature_name_to_placeholder(feature_name, params): """ Get a placeholder for the given feature. Args: - feature_name: name of the feature (<string>). Returns: Return as a tensor tf.placeholder. """ feature_type, shape = ( DATASETS_METADATA[feature_name].dtype, ...
b5785a985517b318e919f03e1f11eaef10fa5827
36,645
from typing import List import re def split_words(value: str) -> List[str]: """Split a string on words and known delimiters""" # We can't guess words if there is no capital letter if any(c.isupper() for c in value): value = " ".join(re.split("([A-Z]?[a-z]+)", value)) return re.findall(rf"[^{DE...
690dfb75c5e22c5d2bbd33797aabe2af41b09518
36,646
from typing import Dict from typing import Any def setup(app: sphinx.application.Sphinx) -> Dict[str, Any]: """Entry point for sphinx theming.""" app.require_sphinx("3.0") app.add_config_value( "pygments_dark_style", default="native", rebuild="env", types=[str] ) app.add_html_theme("furo...
2c196ef86fba7e81f540f4feff3f6c5b924d1940
36,647
def ldns_key_set_pubkey_owner(*args): """LDNS buffer.""" return _ldns.ldns_key_set_pubkey_owner(*args)
f13a90fb29b158254f053523aa387ccf68b41128
36,648
def graph(ich, no_stereo=False): """ inchi => graph """ return automol.convert.inchi.graph(ich, no_stereo=no_stereo)
6925a830838ced5714155b3274517574e5dcdb88
36,649
def get_rancher_services_list(): """ :return: array of all system services """ service_list = [] stacks = get_request( RANCHER_API_URL + RANCHER_API_STACKS_LIST_ENDPOINTS + '?system=false', True ) for stack in stacks['data']: services = get_request( RANCH...
4a9d8076539702fdb754c2a75d9684a712e714b5
36,650