content
stringlengths
22
815k
id
int64
0
4.91M
def set(isamAppliance, dsc, check_mode=False, force=False): """ Updating the tracing levels """ check_value,warnings = _check(isamAppliance, dsc) if force is True or check_value is False: if check_mode is True: return isamAppliance.create_return_object(changed=True, warnings=war...
32,800
def calibrateCameraCharuco(charucoCorners, charucoIds, board, imageSize, cameraMatrix, distCoeffs, rvecs=None, tvecs=None, flags=None, criteria=None): """ calibrateCameraCharuco(charucoCorners, charucoIds, board, imageSize, cameraMatrix, distCoeffs[, rvecs[, tvecs[, flags[, criteria]]]]) -> retval, cameraMatrix, di...
32,801
def submit_annotations(ann_srv_url, annotations, send_zip=False): """ Call the Annotation Storage Service to save annotations. :param ann_srv_url: URL of the annotation service where the annotations will be stored. :param annotations: Annotations to append to the annotations Doc...
32,802
def parse_logfile(logfile): """ Read iotime log entries from logfile Return Table with columns function duration readwrite filename timestamp datetime """ from astropy.table import Table from astropy.time import Time rows = list() with open(logfile) as fx: for line in fx: ...
32,803
def histogram2d(x,y,n=10,range=None,density=False,keep_outliers=False,out=None): """2D histogram with uniform bins. Accelerated by numba x, y: array_like x and y coordinates of each point. x and y will be flattened n : scalar or (nx, ny) number of bins in x and y range : None or ((xmin,xmax)...
32,804
def createSplash(app): """Creates a splash screen object to show while the Window is loading. Return: SplashScreen object. """ uiDir = os.path.dirname(inspect.getfile(KrakenUI)) splashPixmap = QtGui.QPixmap() splashImgPath = os.path.join(uiDir, 'images', 'KrakenUI_Splash.png') splashP...
32,805
def _anatomical_swaps(pd): """Return swap and flip arrays for data transform to anatomical use_hardcoded: no-brain implementation for 90deg rots """ use_hardcoded = True # hardcoded for 90degs if use_hardcoded: if _check90deg(pd) != True: raise(Exception('Not implemented')) ...
32,806
def block_variants_and_samples(variant_df: DataFrame, sample_ids: List[str], variants_per_block: int, sample_block_count: int) -> (DataFrame, Dict[str, List[str]]): """ Creates a blocked GT matrix and index mapping from sample blocks to a list of cor...
32,807
def sparql_service_update(service, update_query): """ Helper function to update (DELETE DATA, INSERT DATA, DELETE/INSERT) data. """ sparql = SPARQLWrapper(service) sparql.setMethod(POST) sparql.setRequestMethod(POSTDIRECTLY) sparql.setQuery(update_query) result = sparql.query() ...
32,808
def filtered_events(request): """Get the most recent year of stocking and pass the information onto our annual_events view. """ dataUrl = reverse("api:api-get-stocking-events") maxEvents = settings.MAX_FILTERED_EVENT_COUNT return render( request, "stocking/found_events.html", ...
32,809
def track_user_session(user=None, request=None): """Creates, filters and updates UserSessions on the core and sends UserSessions to the hub on next login Filter the local UserSession objects per user and get their most recent user_session object If its a LOGIN REQUEST and the UserSession exists, we send t...
32,810
def score(string, goal): """ Compare randomly generated string to the goal, check how many letters are correct and return """ check_counter = 0 string = generate(values) for i in range(len(string)): if string[i] == goal[i]: check_counter += 1 return check_counter
32,811
def validate_parent(): """ This api validates a parent in the DB. """ parent_id = request.json.get('parent_id', None) decision = request.json.get('decision', 0) parent = query_existing_user(parent_id) if parent: parent.validated = decision parent.approver_id = get_jwt_identi...
32,812
def parse_pdu(data, **kwargs): """Parse binary PDU""" command = pdu.extract_command(data) if command is None: return None new_pdu = make_pdu(command, **kwargs) new_pdu.parse(data) return new_pdu
32,813
def alchemy_nodes(mol): """Featurization for all atoms in a molecule. The atom indices will be preserved. Parameters ---------- mol : rdkit.Chem.rdchem.Mol RDKit molecule object Returns ------- atom_feats_dict : dict Dictionary for atom features """ atom_feats_d...
32,814
def generate(*, artifacts: artifacts_types.ModelArtifacts, name: str) -> str: """ Generate the class source from the schema. Args: schema: The schema of the model. name: The name of the model. Returns: The source code for the model class. """ model_artifacts = models_f...
32,815
def main(): """Main function that trains and/or evaluates a model.""" params = interpret_args() # Prepare the dataset into the proper form. data = atis_data.ATISDataset(params) # Construct the model object. model_type = InteractionATISModel if params.interaction_level else ATISModel model...
32,816
def get_rot_mat_kabsch(p_matrix, q_matrix): """ Get the optimal rotation matrix with the Kabsch algorithm. Notation is from https://en.wikipedia.org/wiki/Kabsch_algorithm Arguments: p_matrix: (np.ndarray) q_matrix: (np.ndarray) Returns: (np.ndarray) rotation matrix """ ...
32,817
def test_tfenv_uninstall_arg_takes_precedence(cd_tmp_path: Path) -> None: """Test ``runway tfenv uninstall`` arg takes precedence over file.""" version = "1.0.0" version_dir = cd_tmp_path / version version_dir.mkdir() (cd_tmp_path / TF_VERSION_FILENAME).write_text("0.12.0") runner = CliRunner() ...
32,818
def patch_tex(texfile): """Fix errors in the given texfile, acting on the whole text.""" tex = texfile.read_text(encoding='utf8') tex = tex.replace( r'\begin{equation*}' + "\n" + r'\begin{split}\begin{align}', r'\begin{align*}', ) tex = tex.replace( r'\end{align}\end{split}' ...
32,819
def test_full_with_weeks(): """Test duration""" duration = 'P3Y2M1WT12H11M10S' value = iso8601_to_timedelta(duration) roundtrip = timedelta_to_iso8601(value) assert roundtrip == duration
32,820
def _msrest_next(iterator): """"To avoid: TypeError: StopIteration interacts badly with generators and cannot be raised into a Future """ try: return next(iterator) except StopIteration: raise _MsrestStopIteration()
32,821
def record_export(record=None, export_format=None, pid_value=None, permissions=None): """Export marc21 record page view.""" exporter = current_app.config.get("INVENIO_MARC21_RECORD_EXPORTERS", {}).get( export_format ) if exporter is None: abort(404) options = current_app.config.get(...
32,822
def body_range( operators: List[str], font_changes: List[Tuple]) -> Tuple[Optional[int], Optional[int]]: """given some assumptions about how headers and footers are formatted, find the operations describing the body text of of a page""" # font_changes: (idx, weight, size) thresh = 20....
32,823
def sine(value, default=_SENTINEL): """Filter and function to get sine of the value.""" try: return math.sin(float(value)) except (ValueError, TypeError): if default is _SENTINEL: warn_no_default("sin", value, value) return value return default
32,824
def wmt_affine_base_1e4(): """Set of hyperparameters.""" hparams = wmt_affine_base() hparams.kl_reg = 1e-4 hparams.learning_rate_constant = 2.0 hparams.learning_rate_warmup_steps = 8000 return hparams
32,825
def random_crop_with_constraints(bbox, size, height, width, min_scale=0.3, max_scale=1, max_aspect_ratio=2, constraints=None, max_trial=1000): """Crop an image randomly with bounding box constraints. This data augmentation is used in training of ...
32,826
def unravelContent(originalData): """ This is the primary function responsible for creating an alternate data stream of unraveled data. Args: contentData: Script content Returns: contentData: Unraveled additional content """ contentData = normalize(originalData) loopCount =...
32,827
def fcwrapper(pyenv='python2', instruction=None, data=None, reprint_output=False): """Wrapper to isolate FreeCAD Python 2.7 calls from the Python 3 code base. :param str pyenv: Python interpreter, defaults to 'python2'. :param str instruction: A registered instruction for the QMT FreeCAD mo...
32,828
def quote_verify(data, validation, aik, pcrvalues): """Verify that a generated quote came from a trusted TPM and matches the previously obtained PCR values :param data: The TPM_QUOTE_INFO structure provided by the TPM :param validation: The validation information provided by the TPM :param aik: The...
32,829
def _rectify_base(base): """ transforms base shorthand into the full list representation Example: >>> assert _rectify_base(NoParam) is DEFAULT_ALPHABET >>> assert _rectify_base('hex') is _ALPHABET_16 >>> assert _rectify_base('abc') is _ALPHABET_26 >>> assert _rectify_base(10...
32,830
def loadjson(filename): """ Load a python object saved with savejson.""" if filename.endswith('.gz'): with gzip.open(filename, "rb") as f: obj = json.loads(f.read().decode("ascii")) else: with open(filename, 'rt') as fh: obj = json.load(fh) return obj
32,831
def _write_ffxml(xml_compiler, filename=None): """Generate an ffxml file from a compiler object. Parameters ---------- xml_compiler : _TitratableForceFieldCompiler The object that contains all the ffxml template data filename : str, optional Location and name of the file to save. If...
32,832
def get_utctime( md_keys: List[str], md: Union[pyexiv2.metadata.ImageMetadata, None] ) -> Union[datetime, None]: """Extract the datetime (to the nearest millisecond)""" utctime = None dt_key = "Exif.Image.DateTime" if md is not None: if dt_key in md_keys: utctime = datetime.str...
32,833
def find_file_recursively(file_name, start_dir=getcwd(), stop_dir=None): """ This method will walk trough the directory tree upwards starting at the given directory searching for a file with the given name. :param file_name: The name of the file of interest. Make sure it does ...
32,834
def text_cleaning(any_text, nlp): """ The function filters out stop words from any text and returns tokenized and lemmatized words """ doc = nlp(any_text.lower()) result = [] for token in doc: if token.text in nlp.Defaults.stop_words: continue # if token.is_punct: ...
32,835
def test_answer_2(): """https://stackoverflow.com/questions/63499479/extract-value-from-text-string-using-format-string-in-python""" data = """ name=username1, age=1001 name=username2, age=1002 name=username3, age=1003 """ template = "name={{ name }}, age={{ age }}" parser = ttp(data, template) pars...
32,836
def shave(q,options,undef=MISSING,has_undef=1,nbits=12): """ Shave variable. On input, nbits is the number of mantissa bits to keep out of maximum of 24. """ # no compression, no shave # ------------------------ if not options.zlib: return q # Determine shaving parameters # ...
32,837
def any_none_nan(values: Union[List, np.ndarray, pd.Series, pd.DataFrame, object]) -> bool: """Can be used with a single value or a collection of values. Returns `True` if any item in `values` are `None`, `np.Nan`, `pd.NA`, `pd.NaT` or if the length of `values` is `0`. Args: values: A c...
32,838
def _assert_gat_exists(genomes, gname, aname=None, tname=None, allow_incomplete=False): """ Make sure the genome/asset:tag combination exists in the provided mapping and has any seek keys defined. Seek keys are required for the asset completeness. :param Mapping[str, Mapping[str, Mapping[str, object]]]...
32,839
def get_or_create_package(name, epoch, version, release, arch, p_type): """ Get or create a Package object. Returns the object. Returns None if the package is the pseudo package gpg-pubkey, or if it cannot create it """ package = None name = name.lower() if name == 'gpg-pubkey': retu...
32,840
def sort_dict(value, case_sensitive=False, by='key', reverse=False, index=0): """ 字典排序 :param value: 字典对象 :param case_sensitive: 是否大小写敏感 :param by: 排序对象 :param reverse: 排序方式(正序:True、倒序:False) :param index: 索引号(此处针对 value 为 list 情况下可根据 list 的某一 index 排序) :return: """ if by == 'key...
32,841
async def test_create_user_uses_request_helper_method_with_correct_values(mock_request, jupyterhub_api_environ): """ Does create_user method use the helper method and pass the correct values? """ sut = JupyterHubAPI() await sut.create_user('new_user') assert mock_request.called body_username...
32,842
def initialize_system(name=None): """Initializes a distributed NPU system for use with TensorFlow. Args: name: Name of ops. Returns: The npu init ops which will open the NPU system using `Session.run`. """ return NPUInit(name)
32,843
def zmap_1perm_2samp(X, cat1, cat2=None, rand_seed=-1, fstat=None, name=None): """ une permutation X (D, N, P) K points, N subjects, D dim return: Y (D,) zvalue at each point """ if fstat is None: fstat = hotelling_2samples #name = "MP-Hotelling" if cat2 is None: cat...
32,844
def create_graph(checkpoint): """Creates a graph from saved GraphDef file and returns a saver.""" # Creates graph from saved graph_def.pb. with tf.gfile.FastGFile(checkpoint, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) _ = tf.import_graph_def(graph_def, ...
32,845
def plotDriftmap(ks_directory, sample_rate = 30000, time_range = [0, np.inf], exclude_noise=True, subselection = 50, fig=None, output_path=None): """ Plots a "driftmap" of spike depths over time. This is a useful way to assess overall data quality for an experiment, as it makes probe motion very easy ...
32,846
async def team(ctx, game=None, *, team_message=None): """ Creates a private text channel between you and your opponent(s) """ # exit if no game if game is None: message = "You didn't pick a game! `val` or `lol`" await ctx.send(embed=await embeds.missing_param_error(message)) ...
32,847
def grids_have_same_coords(grid0, grid1): """Whether two `ESMF.Grid` instances have identical coordinates. :Parameters: grid0, grid1: `ESMF.Grid`, `ESMF.Grid` The `ESMF` Grid instances to be compared :Returns: `bool` Whether or not the Grids have identical coordin...
32,848
def _CreateTargetProfDataFileFromProfRawFiles(target, profraw_file_paths): """Returns a relative path to target profdata file by merging target profraw files. Args: profraw_file_paths: A list of relative paths to the profdata data files that are to be merged. Returns: A relati...
32,849
def create_prediction_file(save_dir, identifiers, predictions): """ Create the prediction file. Args: save_dir: The all classes predicted results provided by network identifiers: The data record id predictions: The predict scores """ if not os.path.exists(save_dir): ...
32,850
def run_image_registrator(colmap_binary_path: str, colmap_db_path: str, input_path: str, output_path: str, image_registrator_options: List[str]) -> None: """ run colmap image_registrator: Register new im...
32,851
def get_mwa_eor_spec(nu_obs=150.0, nu_emit=1420.40575, bw=8.0, tint=1000.0, area_eff=21.5, n_stations=50, bmax=100.0): """ Parameters ---------- nu_obs : float or array-like, optional observed frequency [MHz] nu_emit : float or array-like, optional rest frequency...
32,852
def element_add_inplace(x : torch.Tensor, y : torch.Tensor) -> None: """ x += y """ assert x.is_cuda and x.is_contiguous() and x.dtype == torch.half assert y.is_cuda and y.is_contiguous() and y.dtype == torch.half assert x.device == y.device arith.arith_element_add( x.size(0), ...
32,853
def baseModel(data): """ 原有模型 """ formula = "label_code ~ education_num + capital_gain + capital_loss + hours_per_week" model = sm.Logit.from_formula(formula, data=data) re = model.fit() return re
32,854
def load_screen(options: list) -> int: """Callback for loading a screen.""" return get_selection(options)
32,855
def retrieve_url(url): """ Retrieve the URL and parse the response for success/failure and a structured data output. :param url: The fully qualified URL which you want to query. Example: https://www.google.com.au :type url: string :return resp_ok: A True/False boolean to indicate wheth...
32,856
def translate_compile_cli() -> None: """Compile all languages.""" tdir: Path = current_app.config["TRANSLATIONS_DIR"] if tdir.is_dir(): for lang in current_app.config["TRANSLATIONS_DIR"].iterdir(): catalog = lang / _lc_dir() / _po_file() if catalog.is_file(): ...
32,857
def test_model_invalid_task(caplog): """Unit test of model with invalid task.""" caplog.set_level(logging.INFO) dirpath = "temp_test_model_with_invalid_task" Meta.reset() init( dirpath, config={ "meta_config": {"verbose": 0}, }, ) task_name = "task1" ...
32,858
def count_cells(notebook): """ The function takes a notebook and returns the number of cells Args: notebook(Notebook): python object representing the notebook Returns: len(nb_dict["cells"]): integer value representing the number of cells into the notebook A way ...
32,859
def assignments(): """ This is called for the assignments tab on the instructor interface When an assignment is selected get_assignment is called to gather the details for that assignment. """ response.title = "Assignments" cur_assignments = db(db.assignments.course == auth.user.course_id).s...
32,860
def handle(name, userdata, cloud, log, args): """Cloud-init processing function""" tag = MODULE_NAME enabled = False if tag in userdata: try: enabled = bool(userdata[tag]['enabled']) except Exception: LOG.error('%s missing enabled attribute', tag) retu...
32,861
def get_sentences(data: Iterable[JSON_Object], match_by: str) -> Dict[Hash, JSON_Object]: """ Collect sentence objects w.r.t. matching criteria. :param data: Iterable of sentence objects :param match_by: Matching criteria / method :return: Dict of hash: sentence objects """ ...
32,862
def create_infrastructure(aws_key, aws_secret): """Create Redshift infrastructure for this project and set ARN.""" ec2_client, s3_client, iam_client, redshift_client = create_clients( aws_key, aws_secret ) role_arn = create_iam_role(iam_client) create_redshift_cluster(redshift_client, role_a...
32,863
def getInterfaceText(caller_text, callee_method): """ This method parses method text that we grabbed from getMethodSignature for potential interface text that is present. It makes a sort of 'best guess' as to which lines of the caller method text invoke the callee This current implementation ...
32,864
def str2bool(value): """ Args: value - text to be converted to boolean True values: y, yes, true, t, on, 1 False values: n, no, false, off, 0 """ return value in ['y', 'yes', 'true', 't', '1']
32,865
def numeric_float(max_abs: float = 1e3) -> st.SearchStrategy: """Search strategy for numeric (non-inf, non-NaN) floats with bounded absolute value.""" return st.floats(min_value=-max_abs, max_value=max_abs, allow_nan=False, allow_infinity=False)
32,866
def add2dict(dict, parent_list, key, value): """ Add a key/value pair to a dictionary; the pair is added following the hierarchy of 'parents' as define in the parent_list list. That is if parent list is: ['5', '1'], and key='k', value='v', then the new, returned dictionary will have a value: ...
32,867
def transform(x): """ transform x1 x2 ---> 1 x1 x2 x1**2 x2**2 x1x2 |x1 - x2| |x1 + x2| """ ones = np.ones(len(x)) x1 = x[:,0] x2 = x[:,1] x1_sqr = x1**2 x2_sqr = x2**2 x1x2 = x1 * x2 abs_x1_minus_x2 = abs(x1-x2) abs_x1_plus_x2 = abs(x1+x2) return np.stack([ones, x...
32,868
async def get_cities(session: ClientSession) -> AsyncGenerator[City, None]: """ Get cities. :param session: aiohttp session """ url = urljoin(BASE_URL, "Station/GetCities") async with session.get(url, raise_for_status=True) as response: async for row in _iter_rows(response): ...
32,869
def gen_new_contact_json(csv_data): """ Generate json with data about Subnets and theirs Contacts :param csv_data: entry data :return: Stats about created subnets """ dist = {"subnets": csv_data} with open(f'{PATH}{CONTACTS_SUFIX}', 'w') as out_file: out_file.write(json.dumps(dist, i...
32,870
def resize(a, shape): """ if array a is larger than shape, crop a; if a is smaller than shape, pad a with zeros Args: a (numpy array): 2D array to resize shape: desired shape of the return Returns: numpy array: array a resized according to shape """ if...
32,871
def _Run(args, holder, url_map_arg, release_track): """Issues requests necessary to import URL maps.""" client = holder.client url_map_ref = url_map_arg.ResolveAsResource( args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL, scope_lister=compute_flags.GetDefaultScopeListe...
32,872
def resolve_function(module, function): """ Locate specified Python function in the specified Python package. :param module: A Python module :type module: ``types.ModuleType.`` :param function: Name of Python function :type ``str`` :return: Function or None if not found. """ func ...
32,873
def from_table(table, engine, limit=None): """ Select data in a database table and put into prettytable. Create a :class:`prettytable.PrettyTable` from :class:`sqlalchemy.Table`. **中文文档** 将数据表中的数据放入prettytable中. """ sql = select([table]) if limit is not None: sql = sql.limit(l...
32,874
def test_idxgz_load_and_save(tmpdir): """Create idxgz.load() and idxgz.save()""" archive = tmpdir.join("idx.gz") # Test data data = np.array([1, 2, 3]).astype('uint8') print("Before packing:") print("data:", data) print("type(data):", type(data)) print("data.dtype:", data.dtyp...
32,875
def futures_sgx_daily(trade_date: str = "2020/03/06", recent_day: str = "3") -> pd.DataFrame: """ Futures daily data from sgx P.S. it will be slowly if you do not use VPN :param trade_date: it means the specific trade day you want to fetch :type trade_date: str e.g., "2020/03/06" :param recent_d...
32,876
def draw_spectra(md, ds): """ Generate best-fit spectra for all the test objects Parameters ---------- md: model The Cannon spectral model ds: Dataset Dataset object Returns ------- best_fluxes: ndarray The best-fit test fluxes best_ivars: The ...
32,877
def _pivot(p: SimplexMethod.Problem) -> None: """ 对给定问题原址执行转轴操作(基变换) """ main_element = p.a[p.leaving_idx][p.entering_idx] p.a[p.leaving_idx] /= main_element p.b[p.leaving_idx] /= main_element p.base_idx[p.leaving_idx] = p.entering_idx for i in range(len(p.b)): if i != p.leavi...
32,878
def deploy_zebra(suffix=None, usergroup='', subnets=None, security_groups=None, env=None): """deploy tibanna zebra to AWS cloud (zebra is for CGAP only)""" API().deploy_zebra(suffix=suffix, usergroup=usergroup, subnets=subnets, security_groups=security_groups, env=env)
32,879
def get_response( schema, # type: GraphQLSchema params, # type: RequestParams catch_exc, # type: Type[BaseException] allow_only_query=False, # type: bool **kwargs # type: Any ): # type: (...) -> Optional[ExecutionResult] """Get an individual execution result as response, with option to ...
32,880
def _get_status_arrays(): """ Get status for all arrays. """ results = [] try: # Get array(s) status for a site. result = get_status_arrays() if result is not None: results = result return results except Exception as err: message = str(err) ...
32,881
def get_cycle_amplitude(data, cycle, metric_to_use, hourly_period_to_exclude): """ given data (eg results[opposite_pair] [substratification][ substratification_level] ['take_simple_means_by_group_no_individual_mean']) and a cycle and a metric to use (max_minus_min or average_absolute_difference_...
32,882
def submit_job(scheduler_args, command): """Submit a job to the scheduler, returning the supplied job ID. """ cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command status = subprocess.check_output(cl) match = _jobid_pat.search(status) return match.groups("jobid")[0]
32,883
def _download(url: str, dst: str) -> int: """ @param: url to download file @param: dst place to put the file """ file_size = int(urlopen(url).info().get("Content-Length", -1)) r = requests.get(url, stream=True) with open(get_full_data_path(dst), "wb") as f: pbar = tqdm(total=int(r.he...
32,884
def target2line(target, img_size, k, eval=False): """ target: line representetitve in grid [L, grid_h, grid_w] img_size: (width, height): Input image size, PIL Image size eval=False : Default. For inference. Line width not big. eval=True : For iou. Line width is bigger. return line_img """...
32,885
def unmarshal(raw, signature): """Unmarshal objects. The elements of the returned tuple will be of types according to the column *Python OUT* in the :ref:`types summary <ref-types-table>`. :param RawData raw: raw message data :param signature: see :class:`~dcar.signature.Signature` :return: tu...
32,886
def remove_keys(d, to_remove): """ This function removes the given keys from the dictionary d. N.B., "not in" is used to match the keys. Args: d (dict): a dictionary to_remove (list): a list of keys to remove from d Returns: dict: a copy of d, excluding...
32,887
def parse_line(line_str): """ Parse a line from sha1sum output into tuple of hash, directory path and file name. Eg. line '3af30443352a5760cb0f88e619819cee1b1599e0 foo/bar/baz' would be parsed into tuple ('3af30443352a5760cb0f88e619819cee1b1599e0', 'foo/bar', 'baz'). """ line_str = line...
32,888
def get_crypto_quotes(**kwargs): """ Top-level function for obtaining all available cryptocurrency quotes """ return CryptoReader(**kwargs).fetch()
32,889
def mutual_information(y_true, y_pred): """Mutual information score. """ # This is a simple wrapper for returning the score as given in y_pred return y_pred
32,890
def zipf(a, size=None): # real signature unknown; restored from __doc__ """ zipf(a, size=None) Draw samples from a Zipf distribution. Samples are drawn from a Zipf distribution with specified parameter `a` > 1. The Zipf distribution (also known as t...
32,891
def AvgPool(window_shape: Sequence[int], strides: Optional[Sequence[int]] = None, padding: str = Padding.VALID.name, normalize_edges: bool = False, batch_axis: int = 0, channel_axis: int = -1) -> InternalLayerMasked: """Layer construction function for an ave...
32,892
def main(args, special=False): """Główna Funkcja Programu""" verbose_debug_mode = False print("PAiP Web Build System " + version) pwbs_main(args, verbose_debug_mode, special) sys.exit()
32,893
def test_workflow_patch(api_request, mocker): """PATCH a Workflow by its ID""" has_permission = mocker.spy(WorkflowPermission, "has_permission") workflow = WorkflowFactory() template = TemplateFactory() group_refs = [{"name": "group1", "uuid": "uuid1"}] args = ( "patch", "approva...
32,894
def pairwise_distances(x, y): """Computes pairwise squared l2 distances between tensors x and y. Args: x: Tensor of shape [n, feature_dim]. y: Tensor of shape [m, feature_dim]. Returns: Float32 distances tensor of shape [n, m]. """ # d[i,j] = (x[i] - y[j]) * (x[i] - y[j])' # = sum(x...
32,895
def timerange(rstring): """ range from string specifier | 2010-M08 -> range of August 2010 | 2009-Q1 -> range of first quarter, 2009 | 2001-S1 -> range of first "semi" 2001 | 2008 -> range of year 2008 :param rstring: range string :rtype: timerange dictionary """ m_match = ...
32,896
def comp_height_wire(self): """Return bar height Parameters ---------- self : CondType21 A CondType21 object Returns ------- H: float Height of the bar [m] """ return self.Hbar
32,897
def get_update_seconds(str_time: str) -> int: """This function calculates the seconds between the current time and the scheduled time utelising the datetime module. Args: str_time (str): Time of scheduled event taken from user input as a string Returns: int: Returns the seconds...
32,898
def full_name(decl, with_defaults=True): """ Returns declaration full qualified name. If `decl` belongs to anonymous namespace or class, the function will return C++ illegal qualified name. :param decl: :class:`declaration_t` :type decl: :class:`declaration_t` :rtype: full name of declarati...
32,899