content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_html(url): """抓取传入url页面并返回html""" try: with sync_playwright() as p: disable_warnings() # 禁用安全请求警告 browser = p.webkit.launch() # 启用webkit浏览器访问 page = browser.new_page() page.goto(url) page.wait_for_timeout(3000) # 等待网页加载 h...
79c57ef4f0e8f8e1c5711ff09f2eca2b35b26782
3,621,031
import threading def in_main_thread(): """ True when the current thread is the main thread. """ return threading.current_thread().__class__.__name__ == '_MainThread'
82da352928b2af3794a2ee608b2763b98b8a731e
3,621,032
import math def itmlogic_p2p(main_user_defined_parameters, surface_profile_m): """ Run itmlogic in point to point (p2p) prediction mode. Parameters ---------- main_user_defined_parameters : dict User defined parameters. surface_profile_m : list Contains surface profile measure...
8da9c1765112c58494bfd5cc0e139735ae79b93a
3,621,033
def gsl_blas_ssyrk(*args, **kwargs): """ gsl_blas_ssyrk(CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, float alpha, gsl_matrix_float A, float beta, gsl_matrix_float C) -> int """ return _gslwrap.gsl_blas_ssyrk(*args, **kwargs)
19940170fa090ce7fc642c975ea4b887f66e25e4
3,621,036
def address_to_string(b): """Converts an IP address to its string representation. Takes a 4-byte string representing an IP address, and returns a dot-separated decimal representation on the form '123.123.123.123'. """ assert len(b) == 4 b = map(lambda x: str(_decode_byte(x)), b) return '.'...
b22ce9550d9cc7e8354409fc177af27bf87d6dfe
3,621,038
from ..description import WidgetDescription, CategoryDescription from .. import WidgetRegistry def small_testing_registry(): """Return a small registry with a few widgets for testing. """ registry = WidgetRegistry() data_desc = CategoryDescription.from_package("Orange.widgets.data") file_desc =...
99edfa086145e8500383c9b6cf151d8c748c19c2
3,621,039
def fixUnits(object, **kwargs): """Convert output pint units into a proper latex string.""" string = str(object) type = kwargs.get('type', None) unitColor = 'darkBlue' replacements = kwargs.get('replacements', None) if replacements: for old, new in replacements.items(): str...
a1922f296a7d55b989fe5455ed98eb166edeeee7
3,621,040
def get_schema_for_macro_definition(schema): """Return a schema with macro definition directives added in. Preconditions: 1. All compiler-supported and GraphQL-default directives have their default behavior. This returned schema can be used to validate macro definitions, and support GraphQL macro ...
d46d3d0bed4858110fee55e0afb2a058c4b1e0ee
3,621,041
def rect(r, w, deg=False): """ Convert from polar (r,w) to rectangular (x,y) x = r cos(w) y = r sin(w) """ # radian if deg=0; degree if deg=1 if deg: w = np.pi * w / 180.0 return r * np.cos(w), r * np.sin(w)
4b0fee6964dd5d5041a5719a370d77c4a4d7d1ee
3,621,042
from typing import Optional def get_account_ssh_key(name: Optional[str] = None, ssh_key_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAccountSshKeyResult: """ Use this data source to get SSH key information based on its ID...
6ffcef6079c5b72df1474e00149ee42b80fc3a04
3,621,043
def map_l2dist_sinhnormalmech_tCDP(sensitivity, scale, A): """map via the sinhnormal mechanism an L2 distance `sensitivity` with parameters `scale` and `A` to (rho, omega)-tCDP """ rho = (sensitivity / scale) ** 2 / 2 assert 1 < 1 / np.sqrt(rho) <= A / sensitivity return 16 * rho, A / (8 * sen...
8dd6ed4b2bfd6f37beb6ec759b849ab17a465a14
3,621,044
def getMDistance(plug): """ Gets the MDistance value from the supplied plug. :type plug: om.MPlug :rtype: om.MDistance """ return plug.asMDistance()
43cd8dfd2c698ad1cc88771c2c69f3b5e502f202
3,621,045
import torch def create_activation_stats_collectors(model, *phases): """Create objects that collect activation statistics. This is a utility function that creates two collectors: 1. Fine-grade sparsity levels of the activations 2. L1-magnitude of each of the activation channels Args: mod...
9fa705f8c728059e956949662a1aabf0f0cf4643
3,621,046
def get_fach_choices(item_container): """ liefert die Liste der moeglichen Faecher """ ret = [] ret.append((-1, '---')) faecher = get_fach_list(item_container) for fach in faecher: ret.append((fach.fach_id, fach.fach_name)) return ret
11706498d24af113292c2fceae60d2cb72a2d901
3,621,047
import re def isPositive(phrase): """ Returns True if the input phrase has a positive sentiment. Arguments: phrase -- the input phrase to-be evaluated """ return bool(re.search(r'\b(sure|yes|yeah|go)\b', phrase, re.IGNORECASE))
584aa6d03984fbfe0069d3acaa407045b5e86f48
3,621,048
def tree_of_size(size, root, *stops, with_data = True, loc_prefix = 'a', data_prefix = 'd'): """Return expression for a tree segment of size `size` rooted in `root`. If `stops` is non-empty, the given stop nodes are used as the first (but not necessarily left-most) leaves. Warning: Stop nodes are in f...
81f7e05aac561aa826d57b4e6d31f4e80c545977
3,621,049
from typing import Any import operator def less_than(value: Any) -> Matcher[Any]: """Matches if object is less than a given value. :param value: The value to compare against. """ return OrderingComparison(value, operator.lt, "less than")
18be406aac9c7746c0beb7ac4e1ed78de802e197
3,621,050
def get_time_size(rates): """ Get number of time intervals Parameters ---------- Returns ------- out : int Number of time intervals See Also -------- DataStruct """ wgname_keys = list(rates.keys()) mnemo_keys = list(rates[wgname_keys[0]].keys()) return...
c6c496992ef0fe557df302c3c88d9290895cd4a1
3,621,051
def to_pandas(summary, metrics=None, date_key="summary_date"): """ Creates a dataframe from a summary object :param summary: A summary object returned from API :type summary: dictionary of dictionaries. See https://cloud.ouraring.com/docs/readiness for an example :param metrics: The metrics to inc...
3c7a83ddd4cbb3fabd472a8509296187c0c5a79e
3,621,053
def custom_loss(y_true, y_pred, alpha1=1, alpha2=0.5, alpha3=1): """ The designed loss function consists of precision, recall and mean squared error as follows: loss = a1 * precision_loss + a2 * recall_loss + a3 * mae_loss where α 1 , α 2 and α3 are the balance parameters. """ prec, recall =...
2626f652ace99e168f3a2758ac849e4f1b5e1455
3,621,054
def networkx_to_data_dict(graph_nx, node_shape_hint=None, edge_shape_hint=None, data_type_hint=np.float32): """Returns a data dict of Numpy data from a networkx graph. The networkx graph should be set up such that, for fixed shapes `node...
5ceb403d6f6d6fc2b65942f87c051f20c2734808
3,621,055
def compute_attributes_record(service): """ compute the number of attributes needed by this service. """ attribute_records = 1 for characteristic in service.get_characteristics(): # add two attributes, one for the characteristic declaration # and the other for the characteristic value. ...
50f7b10ca13282b2843681605d8177cea84d70f2
3,621,056
def twoQ_clifford_error(ngates, gate_qubit, gate_err): """ The two qubit Clifford gate error given measured errors in the primitive gates used to construct the Clifford (see arxiv:1712.06550). Assumes the error in the underlying gates is depolarizing. Args: ngates: list of the number of gat...
f2e5ef34aa4b1c7363ec0ff2c348d886ed3e8b21
3,621,057
import typing def gather_texture( blender_shader_sockets: typing.Tuple[bpy.types.NodeSocket], export_settings): """ Gather texture sampling information and image channels from a blender shader texture attached to a shader socket. :param blender_shader_sockets: The sockets of the material ...
77826f62db2e0ed998114f3162ad01cc37daf19b
3,621,059
def splitFragP(uriref, punct=0): """split a URI reference before the fragment Punctuation is kept. e.g. >>> splitFragP("abc#def") ('abc', '#def') >>> splitFragP("abcdef") ('abcdef', '') """ i = uriref.rfind("#") if i >= 0: return uriref[:i], uriref[i:] else: ...
cc179fd8f064f3e87f18a9968f6f98ff0d584eb6
3,621,060
from typing import Optional from typing import List def get_scopes_from_groups( config: Config, groups: Optional[List[TokenGroup]] ) -> Optional[List[str]]: """Get scopes from a list of groups. Used to determine the scope claim of a token issued based on an OpenID Connect authentication. Paramet...
c68872f2884b2ec7d169ff94a1868711f03982bd
3,621,061
from typing import List from typing import Dict def get_notifications(refresh: bool = True) -> List[Dict[str, str]]: """ Get a list of notifications. :params refresh: Whether to get new news. If false, the existing notifications will be returned :returns: The list of notifications """ if ref...
03ada7fc18d0e483b75796992be2cb54cf58796d
3,621,062
import ctypes def _convert_double_vector_out( dlist ): """ Convert python list to datum as PyCapsule. Possibly check type of input and handle arrays amd nparrays too. Convert to standard form for C translation to datum. """ _VCL = _find_converter_lib() func = _VCL.double_vector_to_datum ...
390090fa6ef6785c605400c78c42f7e711b4a8b5
3,621,063
def sanitize_name(name): """ Clean-up the given username.""" name = name.strip() # clean up group name = name.replace('- IE', ' -IE') name = name.replace('- MA', ' -MA') for l in [1,2,3,4,5,6,7,8,9]: for g in "AB": name = name.replace(f'IE{l}-{g}', f'IE-{l}{g}') ...
c0618737b0717e6e90c09ab8d2f4f969abb7d891
3,621,064
def _givens_rotation_matrix_entries(a, b): """ Compute matrix entries for Givens rotation. """ r = hypot(a, b) c = a/r s = -b/r return c, s
29bf3891bfdbadde82c9dffebdbba0f9828bc095
3,621,066
def LastAge(): """Age at which mortality becomes 1""" x = 0 while True: if BaseMortRate(x) == 1: return x x += 1
b7dd7f42087c340b1e8ab6f082e8ec33455cf886
3,621,067
import yaml import re def create_kubeconfig_for_ssh_tunnel(kubeconfig_file, kubeconfig_target_file): """ Creates a kubeconfig in which the Server URL is modified to use a locally set up SSH tunnel. (using 127.0.0.1 as an address) Returns a tuple consisting of: - the original IP/Serve...
39c85681486abda0008a040ad13a37032fc182b5
3,621,069
import pandas import math def binomial_distance(left: pandas.Series, right: pandas.Series) -> float: """ Based on the binomial calculations present in the original matlab scripts.""" # Find the mean frequency of each timepoint # index is timepoints, values are frequencies not_detected_fixed_df = pandas.concat([l...
3d9a6c55f225f9360f52c80c11e084c42bc66e48
3,621,070
def sse_pack(d): """ Format a map with Server-Sent-Event-meaningful keys into a string for transport. Happily borrowed from: http://taoofmac.com/space/blog/2014/11/16/1940 For reading on web usage: http://www.html5rocks.com/en/tutorials/eventsource/basics For reading on the format: https://...
5e3f791fc5b2451ff5538c3463674e1e89b80e12
3,621,071
def generate_upstream_solar(year): """ Generate the annual emissions. For solar panel construction for each plant in EIA923. The emissions inventory file has already allocated the total emissions to construct panels and balance of system for the entire power plant over the assumed 30 year l...
2030ed46c66fd0ab9818c4b6b0ef42b435933ceb
3,621,073
def bootstrap_binom_err(k, n, CL=[0.025, 0.975], B=10000, type='percentile'): """ Bootstrap based binomial proportion confidence interval estimator. """ phat = k/n # Special case must be treated separately if k == 0: lower = 0 upper = 1 - (1-CL[1])**(1/n) # Special case must ...
8f9267cd11e28ab4225db613a622a822306a896d
3,621,074
def get_polar(img, msk, cent, r_max, r_min = 0, dr = 1, nPhi = None, dPhi = 1, msk_a = None, msk_w = None, plot = 0): """Returns cartesian images img & msk in polar coordinates pcimg[r,Phi] & pcmsk[r,Phi] @img Image in cartesian coordinates [nx,ny] @msk Mask in cartesian coor...
0582be8a96fa7b4953dd91375f7a604ab4b00da7
3,621,075
import logging def get_logger(name=None): """Get a module for a submodule or the root logger if no name is provided""" return logging.getLogger(domain+'.'+name) if name else logging.getLogger(domain)
dca9fa413f10ed4f93c2233de65cbb72ce507b10
3,621,076
import re def parse_rttm(rttm_path): """Parse audio and query pairs from *.rttm.""" # e.g. "LEXEME sws2013_12345 ... 3.50 1.00 sws2013_dev_123 ..." pattern = re.compile( r"LEXEME\s+(sws2013_[0-9]+).*?([0-9]\.[0-9]+)\s+([0-9]\.[0-9]+)" r"\s+(sws2013_(dev|eval)_[0-9]+)" ) query2aud...
a0fead629b25a89e27d60e902ca93fa409dc3f4a
3,621,077
def get_default_is_leaf_method(): """ returns default method for checking whether a tree should branch further or not ---- Returns ---- result : callable default method to check whether a tree node is a leaf or not """ return pure
d962b3138ddba7660f4d59f7ed89fa21ca08f035
3,621,078
def _separation_angles(katpt_catalogue, target, observer): """Calculate the separation angle between a target. and all the calibrators in the provided catalogue Parameters ---------- katpt_catalogue: katpoint.Catalogue target: ephem.FixedBody observer: ephem.Observer Returns -----...
c7d71fbd2dc15e99fa5b0268f0d79398ef6177fe
3,621,079
import socket def check_proto(host): """ Checks if port 22 or 23 is open, and returns open port number. """ check = socket.socket() response = check.connect_ex((host, 22)) if response == 0: return {'port': 22, 'name': 'ssh'} else: response = check.connect_ex((host, 23)) if ...
2b903cfdad1edab69ba1fcd564540fdbed1dd193
3,621,080
def _touint64(num): """ This is required to convert signed json integers to unsigned. """ return num & 0xffffffffffffffff
9edf75a0bd62ae2c6fb126a9ce1e1b283dfbd52c
3,621,081
import torch def shuffle(images, targets, global_targets): """ A trick for CAN training """ sample_num = images.shape[1] for i in range(4): indices = torch.randperm(sample_num).to(images.device) images = images.index_select(1, indices) targets = targets.index_select(1, indi...
0079304c05293fb68e3af45be7a2e3cbd9564184
3,621,082
def getValidTests(sourceTree): """ get the list of tests and make sure that the tests have all the required parameters. The returned list contains only those that have valid data """ tests = getSections() newTests = tests[:] # [main] is reserved for test suite parameters newTests....
61e06b764475a7b7c0346d3c82fc1bfc9f049e97
3,621,084
from pathlib import Path def read_coords(file_name, base, prefix=""): """Read Ossian's input files with prefix indicating type""" res = {} with open(Path(base, file_name), 'r') as fid: nline = 0 for line in fid: nline += 1 if "=" in line: k, v = line...
6a3e6bf5fe554a13c28a96ab97aa5e14f0cbff13
3,621,085
def group_by_min_key(input_list): """ This function takes a list with tuples of length two inside: [(1,'a'),(1,'b'),('c',True),('d','x')] And return a dict with a list as value: {1:['a','b'], 'c': [True], 'd':['x']} The good thing about this function is that it will find the min key, a...
e2d3964d1a1278613ee46e2207fca86a38aa443f
3,621,086
def get_mean_mask_location(mask): """ Args: - mask Returns: - coordinate of mean pixel location as (x,y) """ coords = np.vstack(np.where(mask == 1)).T return np.mean(coords, axis=0).astype(np.int32)
2819a0b5051e8ebcb891d1c48284dd2105ab9a7f
3,621,087
def get_base_path(base): """returns the path of a base URL if it contains one. >>> get_base_path('http://some.site') == '/' True >>> get_base_path('http://some.site/') == '/' True >>> get_base_path('http://some.site/some/sub-path') == '/some/sub-path/' True >>> get_base_path('http://som...
e678ec67157b3a117e14be5e5b4f42718564fb82
3,621,088
def _make_annotation_lookup(db_links): """Make a lookup dictionary from a list of flat external DB links""" lookup = defaultdict(lambda: defaultdict(set)) for res in db_links: # skip old_bigg_id because it will be in notes if res[0] not in ['old_bigg_id', 'deprecated']: lookup[re...
db8cfaff0b6c2d831b5078efc49d900f17632383
3,621,091
def uniform(shape, dtype=None, min=-1.0, max=1.0, seed=0, name=None): """ This OP returns a Tensor filled with random values sampled from a uniform distribution in the range [``min``, ``max``), with ``shape`` and ``dtype``. Examples: .. code-block:: text Input: shape = [1, 2] ...
faaa2959e1de1f5d43476e124a76bb53cc04c45b
3,621,092
def get_lines_from_file(loc): """Reads the file and returns a list with every line. Parameters: loc (str): location of the file. Returns: list: list containing each of the lines of the file. """ f = open(loc) result= [line.replace("\n", "") for line in f] f.clo...
c05101b94e459346adae553e31d25d46a8475514
3,621,093
def get_path_from_request(request, path: str = None) -> str: """ Return current path from request, excluding language code """ if path is None: path = request.get_full_path() regex_match = language_code_prefix_re.match(path) if regex_match: lang_code = regex_match.group(1) ...
f79baa5e1b5d252a36f231e0acef7d8ef5e680b1
3,621,094
def launch(service_id, project_id, every=EVERY): """ Initialize the module. """ return TutorialPrimitives(service_id=service_id, project_id=project_id, every=every)
81f098de352565fca9f4951e2623f3fa403dd7f1
3,621,095
def draw_keypoints(img_l, top_uvz, color=(255, 0, 0), idx=0): """Draw keypoints on an image""" vis_xyd = top_uvz.permute(0, 2, 1)[idx].detach().cpu().clone().numpy() vis = img_l.copy() cnt = 0 for pt in vis_xyd[:,:2].astype(np.int32): x, y = int(pt[0]), int(pt[1]) # cv2.circle(vis, (...
9b7a309b92ed72f5d489c1d208122d5353a961e3
3,621,096
from typing import Union def polar_angle( snap: Union[SnapLike, Sinks], origin: Quantity = None, ignore_accreted: bool = False ) -> Quantity: """Calculate the polar angle. Parameters ---------- snap The Snap object. origin : optional The origin around which to compute the pola...
84b371acc07cfeef0eab1b57601589dcaf8c4b90
3,621,097
def fstring(c): """Pass the coefficients and return a string corresponding to the ploynomial""" order = len(c) fx = "$f(x) = x^%d" %(order) for n in xrange(order-1): nn = order - 1 - n fx += " + %1.3f x^%d" %(c[nn],nn) fx += " + %1.3f$" %(c[0]) return fx
a5ef2323e69f45c02b5596027e2c871b0837859b
3,621,098
def build(input_reader_config, model_config, training, voxel_generator, target_assigner=None): """Build a dataset""" generate_bev = model_config['use_bev'] without_reflectivity = model_config['without_reflectivity'] num_point_features = model_config['num_point_fea...
1086168623fe40bbb5e18180a089506572cfd2b6
3,621,099
def Rotation_EQJ_GAL(): """Calculates a rotation matrix from equatorial J2000 (EQJ) to galactic (GAL). This is one of the family of functions that returns a rotation matrix for converting from one orientation to another. Source: EQJ = equatorial system, using the equator at the J2000 epoch. Target:...
3eead11002640caf1c7ae67b782b05c33d90d741
3,621,100
from pathlib import Path import tqdm def query_copernicus_hub(aoi, username, password, hub, **kwargs): """Query Copernicus Open access Hub. :param aoi: (str) Geojson Area of interest url :param username: (str) Username to use for API connection :param password: (str) Password to use for API connectio...
b69e54797e2f12699a586d2e6ab9f8081fbb51d7
3,621,101
from saq.database import get_db_connection def delete_password(key): """Deletes the given password from the database. Returns True if the password was deleted.""" with get_db_connection() as db: c = db.cursor() c.execute("DELETE FROM `encrypted_passwords` WHERE `key` = %s", (key,)) db....
09ac6784ddb34f42a455ce920b2589049b28d478
3,621,102
def StandardMols(mols, n_jobs=1): """ """ mols = mols if type(mols) is not Chem.rdchem.Mol else [mols] n_jobs = n_jobs if n_jobs>=1 else None pool = Pool(n_jobs) sm = pool.map_async(StandardMol, mols).get() pool.close() pool.join() return sm
dc238cafc4b9676392fb3a38d032368a471369fb
3,621,103
def af_to_maf(af): """ Converts an allele frequency to a minor allele frequency Args: af (float or str) Returns: float """ # Sometimes AF == ".", in these cases, set to 0 try: af = float(af) except ValueError: af = 0.0 if af <= 0.5: return af ...
aed0361218fbb8ebda43b2abfd6638d2f9df2431
3,621,104
from lasagne import layers from nolearn.lasagne import NeuralNet from .shape import ReshapeLayer import logging def generate_nnet(feats): """Generate a neural network. Parameters ---------- feats : list with at least one feature vector Returns ------- Neural network object """ # ...
40a3a36b2100ddd15684088e991ee16568ebd55b
3,621,105
def validate_auth(config: ConfigType) -> ConfigType: """Validate presence of CONF_ACCESS_TOKEN when CONF_DEVICE_CLASS=tv.""" token = config.get(CONF_ACCESS_TOKEN) if config[CONF_DEVICE_CLASS] == "tv" and not token: raise vol.Invalid( f"When '{CONF_DEVICE_CLASS}' is 'tv' then '{CONF_ACCES...
7740cef5d91e33cd5f4d54fca78ab04fd3ac4268
3,621,107
def GetBuildShortBaseName(target_platform): """Returns the build base directory. Args: target_platform: Target platform. Returns: Build base directory. Raises: RuntimeError: if target_platform is not supported. """ platform_dict = { 'Windows': 'out_win', 'Mac': 'out_mac', 'Li...
0bbbad4de3180c2ea51f5149cc3c2417a22b63e9
3,621,108
def build_B_from_A(A, nodes=None): """ Create the numpy adjacency tensor of a networkX graph. Parameters ---------- A : list List of MultiDiGraph NetworkX objects. nodes : list List of nodes IDs. Returns ------- B : ndarra...
0d00cc4ae7a3d2d1de70c5703d2b457d032b7ce8
3,621,109
def get_sort_order(ds_spec): """ Find how quickly the spectroscopic values are changing in each row and the order of rows from fastest changing to slowest. Parameters ---------- ds_spec : 2D HDF5 dataset or numpy array Rows of indices to be sorted from fastest changing to slowest R...
152ccc7e58f1787f1231f8793791496ef98dc07e
3,621,110
import traceback import calendar import time def generate_error(request, cls, e, tb, include_traceback=False): """ Builds an L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} based on the last traceback and the request that was sent. """ if hasattr(cls, '_amf_code'): code = cls._amf_code...
39807433d9a43f89b09dd6c3cd575dedc779f004
3,621,111
def reads(text, ext, format_name=None, rst2md=False, as_version=4, **kwargs): """Read a notebook from a string""" if ext == '.ipynb': return nbformat.reads(text, as_version, **kwargs) format_name = read_format_from_metadata(text, ext) or format_name if not format_name: format...
220bb2c6a9e8932858d780a87eab2a6dd8928c6d
3,621,112
def make_wildcard(title, *exts): """Create wildcard string from a single wildcard tuple.""" return "{0} ({1})|{1}".format(title, ";".join(exts))
0634c450f43cc779431f61c2a060cea7e02f6332
3,621,113
def _getFields(qset=None, model=None): """ returns a list of fields for specified QuerySet or Model """ if hasattr(qset, '_meta') and getattr(qset, '_meta') != None: fields = qset._meta.fields elif hasattr(qset, 'model') and getattr(qset, 'model') != None: fields = qset.model._meta.f...
8760a802f810d49b51fcb02a087f1ea46b8b61bf
3,621,114
from pathlib import Path def dir_files(path, pattern="*"): """ Returns all files in a directory """ if not isinstance(path, Path): raise TypeError("path must be an instance of pathlib.Path") return [f for f in path.glob(pattern) if f.is_file()]
5dbeeec6fe72b70381afb52dcbbea55613a37d49
3,621,115
def fix_while_loop(x): """Change Javascript for loop to Python for loop for(var i = 0fi < x.length;i++){" --> "for i in range(0,len(x),1): Args: x (str): A string with Javascript syntax. Returns: [str]: Python string Examples: >>> from ee_extra import fix_for_loop ...
962d9e2cb74ac62f2a5c641d2397369434c1b44a
3,621,116
def io_connection_pattern(inputs, outputs): """Return the connection pattern of a subgraph defined by given inputs and outputs.""" inner_nodes = io_toposort(inputs, outputs) # Initialize 'connect_pattern_by_var' by establishing each input as # connected only to itself connect_pattern_by_var = {} ...
08c395de6bf8e5068ad0c9fa3c19155084441994
3,621,117
def pool_forward(A_prev, hparameters, mode = "max"): """ Implements the forward pass of the pooling layer. Parameters: ----------- A_prev: tensor of shape (m, n_H_prev, n_W_prev, n_C_prev) Input data. hparameters: dictionary Contains "f" and "stride". ...
62edf0e2696a1588878dcd4ccbb8521faf576dda
3,621,119
def myDownsample(y, N) : """ yds = myDownsample(y,N) yds is y sampled at every Nth index, starting with yds[0]=y[0] with y[range(0,len(y),N)]. Implementing Matlab's downsample. Ted Golfinopoulos, 7 June 2012 """ return y[range(0,len(y),N)]
0d39f37f4e3a5528f087921e6a4993ea6bf2981c
3,621,120
def _norm_args(norm): """ Returns the proper normalization parameter values. Possible `norm` values are "backward" (alias of None), "ortho", "forward". This function is used by both the builders and the interfaces. """ if norm == "ortho": ortho = True normalise_idft = Fals...
e781c894c9d333fdbdf326120b1417b44dfc5181
3,621,121
def get_next_point_in_trace(trace: LineString, point: Point) -> Point: """ Determine next coordinate point towards middle of LineString from point. """ coord_points = get_trace_coord_points(trace) assert point in coord_points if point == coord_points[-1]: return coord_points[-2] if p...
07becf63ae6bdb03e3e9dc1f7982d3af3a28031a
3,621,123
def reduced_quantity(a_quantity, b_quantity): """ Returns the reduced mass of two particles. Examples: ``` >>> reduced_quantity(1*u.kg, 1*u.kg) <Quantity(0.5, 'kilogram')> >>> reduced_quantity(1*u.kg, 20*u.kg).m 0.9523809523809523 >>> reduced_quantity(1, 200)...
be48533c6cfd1b2063ee149f11071496661631e0
3,621,124
def expected_value(values, state, action, discount=0.9): """Calculate expected value for a given action :param state: state which value is updated :type state: tuple :param action: action taken in this state :type action: int :param discount: discount :type discount: float :return: new ...
48832bf7d55fa7deb3a29e0ce9923bcfc57841f8
3,621,125
def tf(*args, **kwargs): """ Create a transfer function model of a system. :param args: pass in num :type args: TransferFunction | List[numbers.Real] | numbers.Real :return: the transfer function of the system :rtype: TransferFunction :Example: >>> from tcontrol imp...
4f0cec88b55c932479063a506bbeb734dd392a8c
3,621,126
import torch def all_pair_iou(boxes_a, boxes_b): """ Compute the IoU of all pairs. :param boxes_a: (n, 4) minmax form boxes :param boxes_b: (m, 4) minmax form boxes :return: (n, m) iou of all pairs of two set """ N = boxes_a.size(0) M = boxes_b.size(0) max_xy = torch.min(boxes_a[:...
1ca948e4a16016efa694d97c4829fcdfbc29e20d
3,621,127
def get_matching_list_from_graph(graph): """ :param graph: nx.Graph(); each edge should have an attribute "color" :return: List of matching; each matching is an nx.Graph() representing a sub-graph of "graph" """ degree = get_graph_degree(graph) colors = [i for i in range(degree + 1)] ...
e73b2e72fe5d9ed480c52c4904564601bf890148
3,621,128
def remove_zeros(res_array): """ Erase all zeros in res_array and return (reduced) array without zeros. Parameters ---------- res_array : np.array Numpy results array Returns ------- res_no_zeros : np.array Numpy results array without zeros (shorter than res_array, if z...
5c85389f5bdaade3702b8218c793945c89ad018c
3,621,129
def butter_lowpass(cutoff, fs, order=5): """ This is based on butter_bandpass """ nyq = 0.5 * fs normal_cutoff = cutoff / nyq b, a = ssig.butter(order, normal_cutoff, btype="low", analog=False) return b, a
36a456f627ee5fccd3f0d0931ae894cc40576676
3,621,130
import warnings def instantaneous_phase_shift(analytic_sig, time_vect, carrier_frequency): """ For a signal $x(ray) = A * exp(i (2 pi f_0 ray + phi(ray)))$, returns phi(ray) in [-pi, pi[. Parameters ---------- analytic_sig: ndarray time_vect: ndarray carrier_frequency: float Returns ...
ffb8ae79e9f06e2c8dc30c949031d2fe4611527b
3,621,131
def get_p0_gaussian(x, y): """Estimate (x0, dV, Tb) for the spectrum.""" if x.size != y.size: raise ValueError("Mismatch in array shapes.") Tb = np.max(y) x0 = x[y.argmax()] dV = np.trapz(y, x) / Tb / np.sqrt(2. * np.pi) return x0, dV, Tb
6ec338b7e441351aea21b31d526153fcc9a1422d
3,621,132
def list_mendeley_accounts_user(auth): """ Returns the list of all of the current user's authorized Mendeley accounts """ provider = MendeleyCitationsProvider() return provider.user_accounts(auth.user)
b8373dde5015d33eabb58b21d9a052b49303f492
3,621,133
import ipaddress def _verify_address(addr): """Function verifies that address is valid IPv4 address Args: addr : address of machine Return: boolean value defining validity of address """ try: ipaddress.ip_address(unicode(addr)) return True except ValueError: ...
24232851b7aa1c7d45b4d0be45a87cd5239c9917
3,621,135
def output_reduce_list(path_list, force=False): """Generates structure file with protons from a list of structure files.""" output_paths = [] for path in path_list: output_path = output_reduce(path, force=force) if output_path: output_paths.append(output_path) return output_p...
32d364442e623bb32aae19008e5e7d41e089d678
3,621,137
def asStructuredText(I, munge=0): """ Output structured text format. Note, this will whack any existing 'structured' format of the text. """ r = [I.getName()] outp = r.append level = 1 if I.getDoc(): outp(_justify_and_indent(_trim_doc_string(I.getDoc()), level)) bases = [base ...
b28587313a825ee487bc230c1faaa105de19aa38
3,621,138
def current_distribution_by_website(site): """ Reads the checker framework version from the checker framework website and returns the version of the current release """ print 'Looking up checker-framework-version from %s\n' % site ver_re = re.compile(r"<!-- checker-framework-version -->(.*),") ...
a35f66ce2ddda5ecd5e851d859e3ac3e9928d830
3,621,139
def make_hyperspherical_classification_loss(prototypes): """ Args: prototypes: (num_classes, embed_dim) """ def _get_prototypes(labels): return tf.tensordot(labels, prototypes, [[1], [0]]) def loss(preds, labels): """ Args: preds: (Batch, embed_d...
d08cc12021eb82dbe7adf230bad52c8fbd27b9d0
3,621,141
def nz_MgCLN_Gayer( lam: float, T: float, ax: str=None, ): """ Refractive index for MgCLN, based on Gayer et al, APB 2008 Parameters ---------- lam: wavelength (lambda) [um] T: Temperature [Celsius Degrees] ax: polarization Returns ------- nz: Refractive...
b13cd027840dd47ee20bce11e90c8789ee90f3ab
3,621,142
from pathlib import Path import logging def export_corpora( corpus_ids, granularity, corpora_folder, filename, no_download=False ): """ Generates a single JSON file with the chosen granularity for all of the selected corpora :param corpus_ids: IDs of the corpora that will be exported :par...
7a99ce5b7d1f7b8ca1a5060bf5fb02b3aa825954
3,621,143
from typing import Iterable from re import T from typing import Callable from typing import Tuple from typing import Iterator import itertools from typing import cast def all_pairs_iterator(values: Iterable[T], with_replacement: bool = True, where: Callable[[Tuple[T, T]],...
667f5ffe01581ac29bf26f5b2d03f08552bd3347
3,621,144
def syllable_tokenize(text): """ :param str text: input string to be tokenized :return: returns list of strings of syllables """ syllables = [] if text: words = word_tokenize(text) trie = create_custom_dict_trie(custom_dict_source=syllable_dict()) for word in words: ...
7b60885d3918c21e2d63cf48f0cc3c60a3b32c5d
3,621,145
from src import bcrypt def create_sponsor(loggedin_user): """ Creates a new Sponsor manually and bypasses email verification. --- tags: - admin summary: Create Sponsor requestBody: content: application/json: schema: $ref: '#/compo...
acd9c2f68131f71ca7c719eb22022eb5897f1bf5
3,621,146
def get_empty_theme(): """Create object that contains empty theme.""" return { 'theme': {}, 'background': bytearray() }
fc129d109ef2677b41d9a0f608fd580b63c45c8e
3,621,147