content
stringlengths
22
815k
id
int64
0
4.91M
def main_arg(): """ run all functions of heart_rate_monitoring file :param: arg arguments from argparse :return file: return user inputted file :return brady: return user inputted bradycardia value :return tachy: return user inputted tachycardia value :return signal: return user inputted signal...
5,310,300
def test_flag_staker_tag(): """Test user choosing to use different staker.""" runner = CliRunner() result = runner.invoke(cli, ["-st", "thisdoesnotexist", "report"]) assert result.exception assert result.exit_code == 1 expected = "No staker found for given tag, using default" assert expect...
5,310,301
def get_pager_command(text=None): """ Get the command to show a text on the terminal using a pager. :param text: The text to print to the terminal (a string). :returns: A list of strings with the pager command and arguments. The use of a pager helps to avoid the wall of text effect where the user ...
5,310,302
def make_2axis_graph(): """Makes a 2 axis graph when user changes the X or Y axis selection""" d = curdoc() _remove_fig(d) graph_val = d.get_model_by_name(GRAPH_SELECTION).value model_id, message_name, _ = run_handlers.get_modelid_messagename_type(d) xval = d.get_model_by_name(X_AXIS_SELECTION)...
5,310,303
def get_business_or_personal_relationship(): """Saves as (B) or (P). This is the relationship type the user has to the contact""" business_or_personal_relationship = input("Business or Personal | Enter Your Relationship to the Contact (enter B for business) or (enter P for personal), Then Press Enter: ") i...
5,310,304
def group_files(filenames, filename_re=FILENAME_OPFILE_RE, verbose=False): """ Group all filenames by their session ID, camera (aka recording), resolution (i.e. width x height) and frame index. :param filenames: List of filenames to be grouped together. :param filename_re...
5,310,305
def p_indented_comma_list2(p): """indented_classifiers_list : INDENT classifiers DEDENT """ p[0] = p[2]
5,310,306
def create( name: str, /, **fields: Field[Any], ) -> Type[Structure]: """ Functional API for creating structure. :param name: structure type name :param fields: structure fields """ cls = cast(StructureMeta, StructureImpl) bases = (cls,) metaclass = cls.__class__ att...
5,310,307
def from_pretty_midi( midi: PrettyMIDI, resolution: int = DEFAULT_RESOLUTION, mode: str = "max", algorithm: str = "normal", collect_onsets_only: bool = False, first_beat_time: Optional[float] = None, ) -> Multitrack: """Return a Multitrack object converted from a PrettyMIDI object. Pars...
5,310,308
def test_fetch_outputs_empty_path( mocker, mocked_fetch_nodes, mocked_fetch_output_path, mocked_fetch_output_template_config, mocked_is_enabled, mocked_fetch_file_type, mocked_fetch_file_types, mocked_fetch_colorspace, mocked_has_multiple_views, ): """Return output context objects when node path is ...
5,310,309
def assign_role(): """ This API assigns one role to the user in the request """ user_id = request.json.get('user_id', None) role = request.json.get('role', None) user = query_validated_user(user_id) if user: user.role = role db.session.add(user) db.session.commit() ...
5,310,310
def test_fold_inexact_positions(get_model, models_close): """ Test that creating a supercell model and then folding it back creates the same model. """ model = get_model(0.1, 0.3) model.uc = np.array([[1, 0, 0.5], [0.1, 0.4, 0.0], [0.0, 0.0, 1.2]]) model.pos = np.array([[0, 0, 0], [0.5, 0.5,...
5,310,311
def set_plt_params(): """ Sets pyplot parameters """ plt.rcParams['figure.figsize'] = [12, 9] plt.rcParams['lines.markersize'] = 8 plt.rcParams['axes.labelsize'] = 20 plt.rcParams['xtick.labelsize'] = 25 plt.rcParams['ytick.labelsize'] = 25 plt.rcParams['legend.fontsize'] = 20
5,310,312
def material_yellow_rubber(emission=DEFAULT_EMISSION, face=GL_FRONT_AND_BACK): """Material de goma amarillo""" glMaterialfv(face, GL_AMBIENT, [0.05, 0.05, 0.0, 1.0]) glMaterialfv(face, GL_DIFFUSE, [0.5, 0.5, 0.4, 1.0]) glMaterialfv(face, GL_SPECULAR, [0.7, 0.7, 0.04, 1.0]) glMaterialfv(face, GL_SHIN...
5,310,313
def _create_tmp_customize(bases, prefix=None): """Create a temporary """ temp_dir = TemporaryDirectory(prefix=prefix) # kustomize only recognizes relative paths, so convert that bases = [os.path.abspath(base) for base in bases] bases = [os.path.relpath("/", base) + base for base in bases] wit...
5,310,314
def segment(image): """ Segment the image -- return the scores. :param image: An image with shape 3 x 360 x 480 (sized to match the net) :return: The output scores (len(LABELS) x 512 x 512) """ assert image.shape == (3, 360, 480) net().blobs['data'].data[...] = np.array([image]) results =...
5,310,315
def get_reg_name(*args): """ get_reg_name(int reg, size_t width, char buf, int reghi=-1) -> ssize_t get_reg_name(int reg, size_t width, char buf) -> ssize_t """ return _idaapi.get_reg_name(*args)
5,310,316
def ast_for_factor(factor: 'Ast', ctx: 'ReferenceDict'): """ factor ::= [unaryOp] invExp [suffix]; """ assert factor.name is UNameEnum.factor unary_op: 'Tokenizer' = None suffix: 'Tokenizer' = None n = len(factor) if n is 3: unary_op, inv, suffix = factor elif n is 2: ...
5,310,317
def spherical_to_cartesian_4d(thetas, r=1.0): """ Converts points on the hypersphere S^3 in R^4 given in spherical coordinates to their cartesian value. :param thetas: [N, 3] thetas = [theta_1 | theta_2 | theta_3], with theta_i [N, 1] 0 <= theta_1 < 2 * pi and 0 <= theta_2 < pi ...
5,310,318
def sheets_get_ranges(spreadsheet_id, sheet_ranges): """ Returns a Value Ranges for the input ranges. See Sheets API Documnetation for rangee syntax Sample: ['Sheet1', 'Sheet2] returns all values on these sheets """ service = get_sheets_service() response = service.spreadsheets().value...
5,310,319
def Json(v: Any, fname: str, lazy: List[Any]): """ Default JSON encoder using ``json.dumps``. This version encodes ``None`` as json null value. """ return text_escape(dumps(v))
5,310,320
def sem_id_get(obs_id): """ Retrieves all the sem_ids associated with an observer http://vm-webtools.keck.hawaii.edu:50001/v0/semesterIds/?obs_id=2003 :param obs_id: observer id :type obs_id: int :rtype: List[str] """ # authenticate, # use a master id in check_obs_id or check ==...
5,310,321
def test_get_role_for_admin(): """ Check that _get_user_role() returns[PROFILE_ADMIN] only for a given superuser """ user = UserFactory.create(is_superuser=True) joboffer = JobOfferFactory.create() assert _get_roles(joboffer.company, user) == {ROLE_ADMIN}
5,310,322
def welcome(): """Print a welome message.""" print "Python %s %s, %s" % (NAME, VERSION, BUILDDATE) print "A %s" % DESCRIPTION print return()
5,310,323
def _update_improper_axes( n, ax, axes, atomcoords, groups, rtol, atol, normalize=False # found axes ): """Update axes with ax and return it. Helper function for _get_improper_axes. """ if normalize: norm = np.linalg.norm(ax) if np.isclose(norm, 0.0, rtol=rtol, atol=atol): ...
5,310,324
def resolver_for(domain, mname): """Return a resolver object whose nameservers are obtained by asking the SOA MNAME (master name) for its addresses and listing the remaining NS addresses after that. Master is assumed to be most up-to-date, but may not always be reachable.""" addresses = [] maybe...
5,310,325
def plot_correlogram(bin_values, bin_edges, ax): """Plots output from :py:func:`auto_correlation` or :py:func:`cross_correlation` to `matplotlib` axes provided. :param numpy.ndarray bin_values: correlation values to plot, shape (n_bins,) :param numpy.ndarray bin_edges: x-axis edges for values in bin_va...
5,310,326
def _clone_github_repo(url, out_dir): """Clones a GitHub repository. Args: url (str): The link to the GitHub repository out_dir (str): The output directory for the cloned repository. """ repo_name = os.path.basename(url) # url_zip = os.path.join(url, 'archive/master.zip') url_z...
5,310,327
def plotData(X, y): """ Plots the data points X and y into a new figure. Plots the data points with * for the positive examples and o for the negative examples. Parameters ---------- X : array_like An Mx2 matrix representing the dataset. y : array_like Label values for the ...
5,310,328
def div(client, symbol, timeframe="6m", col1="open", col2="close"): """This will return a dataframe of Vector Arithmetic Div for the given symbol across the given timeframe Args: client (pyEX.Client); Client symbol (string); Ticker timeframe (string); timeframe to use, for pyEX....
5,310,329
def create_possible_expected_messages(message_template, expected_types): """ Some error messages contain dictionaries with error types. Dictionaries in Python are unordered so it makes testing unpredictable. This function takes in a message template and a list of types and returns a list that contai...
5,310,330
def chkSort(array): """Make sure sort actually did its job""" for i in range(0, len(array)-2): if array[i] > array[i+1]: print("{} is not greater than {} for indices=({},{})").format(array[i+1], array[i], i, i+1) return False return True
5,310,331
def click_button(driver, locator): """function tries to find the locator passed and clicks on it Args: driver (WebDriver): Selenium webdriver object locator (str): locator tag that uniquely identifies an element in the DOM """ try: button = driver.find_element_by_css_selector(lo...
5,310,332
def fetch_dss_files(uuid): """ Initiate checking out a file for download from the HCA data store (DSS) parameters: - name: uuid in: path type: string description: UUID of the file to be checked out - name: fileName in: query type: string ...
5,310,333
def _save_matrix(matrices, name, form, matrix): """save the matrix""" if name in matrices: # there are duplicate matrices with the same name (e.g., the QHH) form0, matrix0 = matrices[name] if isinstance(form0, int): assert isinstance(form0, int), form0 form2 = [fo...
5,310,334
def trajectories(fig, trajectories, plot_mode=PlotMode.xy, title="", subplot_arg="111"): """ high-level function for plotting multiple trajectories :param fig: matplotlib figure :param trajectories: instances or iterables of PosePath3D or derived - if it's a dictionary, the keys (na...
5,310,335
def topology_tiscali2(**kwargs): """Return a scenario based on Tiscali topology, parsed from RocketFuel dataset Differently from plain Tiscali, this topology some receivers are appended to routers and only a subset of routers which are actually on the path of some traffic are selected to become ICN rou...
5,310,336
def eval_final_hand(cards: List[Card]) -> Optional[Tuple[str, PokerHand, int]]: """ Turns a list of 7 cards into a string representation of the best hand possible with those 7 """ cards.sort(reverse=True) # Get valid five card combinations five_card_hands = list(combinations(cards, r=5)) # For eac...
5,310,337
def grab_color() -> Tuple[Tuple[int, int, int], Tuple[int, int]]: """ returns a list with a tuple containing the RGB value of the most present color around the mouse and the position at the time of measurement """ pos = mouse.get_position() m = 2 rect = (pos[0] - m, pos[1] - m, pos[0] + m, ...
5,310,338
def test_debug(script, args): """ Check simple option cases. """ args = ['debug'] + args result = script.pip(*args) stdout = result.stdout assert 'sys.executable: ' in stdout assert 'sys.platform: ' in stdout assert 'sys.implementation:' in stdout tags = pep425tags.get_supporte...
5,310,339
def get_dihedral_angle1(p0,p1,p2,p3): """http://stackoverflow.com/q/20305272/1128289""" p = [p0, p1, p2, p3] b = p[:-1] - p[1:] b[0] *= -1 v = numpy.array( [ v - (v.dot(b[1])/b[1].dot(b[1])) * b[1] for v in [b[0], b[2]] ] ) # Normalize vectors v /= numpy.sqrt(np.einsum('...i,...i', v, v)).re...
5,310,340
def calc_delta_lampams2( multipanel, constraints, delta_lampams, pdl, n_plies_to_optimise): """ calulates all ply partial lamination parameters in a multipanel structure that correspond to a specific ply drop layout INPUTS - multipanel: multipanel structure - delta_lampams: al...
5,310,341
def merge_user_data(spark, table_type, table_num, start_num=0): """ :param table_type: 【str】 'click' or 'top' or 'play' :return: 【dataframe】 返回每种行为数据所有表的merge表 """ spark.sql("use {}".format(user_pre_db)) if start_num == 0: ret = None else: # 本来想运行完,删除掉改过名的表merge_{}_{},但在保存前删除...
5,310,342
def measRefProbeCur(baseDir, vkV, det, rptFil, debug=False): """measRefProbeCur(baseDir, vkV, det, rptFil, debug=False) Measure the relative prove current for Cu reference spectra in the baseDir/spc/refs/%gkV/ directory using the Cu standard spectra in baseDir/msa/std/%gkV/Cu.msa for a list (vkV) of e0 values for ...
5,310,343
def fill_ip(entry): """Fill GtkEntry with the local IP. Can be called from a thread.""" try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) addr = s.getsockname()[0] s.close() except EnvironmentError: addr = "?.?.?.?" def idle_fi...
5,310,344
def get_version_from_pkg_info(): """Get the version from PKG-INFO file if we can.""" pkg_info_path = os.path.join(os.path.dirname(__file__), 'PKG-INFO') try: pkg_info_file = open(pkg_info_path, 'r') except (IOError, OSError): return None try: pkg_info = email.message_...
5,310,345
def gridToList(box): """ :summary: Reads text fields into a list for racksorter module :param QGroupBox box: group box to read the grid from :rtype: list :return: racksorter module-ready list of the permutation """ l = [] layout = box.layout() positions = [(i,j) for i in range(confi...
5,310,346
def get_unavailable_agents(day): """Determine agents with no availability for a given day.""" day_number = day.weekday() unavailable = set() for handle in df_agents.index: if len(df_agents.loc[handle, "slot_ranges"][day_number]) == 0: unavailable.add(handle) print(f"\nUnavailab...
5,310,347
def test_create_item_raster_with_gcps(): """Should return a valid item with raster properties.""" src_path = os.path.join(PREFIX, "dataset_gcps.tif") item = create_stac_item( src_path, input_datetime=input_date, with_raster=True, with_proj=True ) assert item.validate()
5,310,348
def compare_descriptor_types(a, b): """Compare two metric types to sort them in order.""" # pylint: disable=invalid-name a_root = a['type'][len(CUSTOM_PREFIX):] b_root = b['type'][len(CUSTOM_PREFIX):] return (-1 if a_root < b_root else 0 if a_root == b_root else 1)
5,310,349
def info( image_name: str = typer.Argument(..., help="The name of the image"), output_format: Optional[str] = typer.Option( None, "-o", "--output-format", help="Ouput format [json]" ), ): """ Show information for an image stored in a docker registry """ registry, repository, tag = Do...
5,310,350
def get_image(image) -> Image.Image: """ Gives back the given image as a PIL.Image.Image instance Args: image: the given image, it can be a filepath (str, bytes or Path), an URL (which will be downloaded), a BytesIO or a PIL.Image.Image instance Returns: A PIL.Image.Image insta...
5,310,351
def get_worksheet(ts: ThoughtSpot, connection_guid: str, worksheet_guid: str) -> Worksheet: """ :param ts: The connection to ThoughtSpot for API calls. :param connection_guid: GUID for the connection with the table to map to (not always the old connection) :param worksheet_guid: GUID for the worksheet t...
5,310,352
def run_grover_search(number_of_qubits, oracle, oracle_args): """ Uses Grover's quantum search to find the single answer to a problem with high probability. Parameters: number_of_qubits (int): The number of qubits that the oracle expects (the number of qubits that the answer will co...
5,310,353
def compute_epsilon(target_delta, steps, noise_multiplier, batch_size, dataset_size): """Computes epsilon privacy value for given hyperparameters.""" if noise_multiplier == 0.0: return float("inf") orders = [1 + x / 10.0 for x in range(1, 100)] + list(range(12, 64)) sampling_probability = batch...
5,310,354
def findCisIndexes(cisSplits, protSeq, overlapFlag, maxDistance): """ Called by cisOrigins(), this function returns the location data of where different pairs of cisSplits (which combine to form a given peptide) exist in a protein sequence. The output data structure is a series of embedded lists. The ou...
5,310,355
def export_selected_games_pgn_no_comments(grid, filename): """Export selected records in PGN export format excluding comments. If any records are bookmarked just the bookmarked records are exported, otherwise all records selected for display in the grid are exported. """ if filename is None: ...
5,310,356
def add_dimensions(G, naming_convension: NamingConvension = None) -> list: """ Walks graph setting all edge names and dimensions """ if naming_convension is None: naming_convension = DefaultNamingConvension(G) for edge in G.edges(): edge.params = None steps = [] indexes = {'inpu...
5,310,357
def add_day(date: str, format_='%Y-%m-%d', to_str=False, **kwargs) -> datetime: """一个日期加多少天或者时间 :param date: 一个正确的日期 :param format_: 日期格式化 :param to_str: 是否打印字符串 :param kwargs: 可以填写 :days=xx,seconds=xx,microseconds=xx,milliseconds=xx,minutes=xx,hours=xx,weeks=xx :return: 被加后的日期 """ start...
5,310,358
def fetch_swiss_exchanges(session, target_datetime, logger): """Returns the total exchanges of Switzerland with its neighboring countries.""" swiss_transmissions = {} for exchange_key in ['AT', 'DE', 'IT', 'FR']: exchanges = ENTSOE.fetch_exchange(zone_key1='CH', ...
5,310,359
async def test_update_race( http_service: Any, token: MockFixture, context: dict ) -> None: """Should return No Content.""" headers = { hdrs.CONTENT_TYPE: "application/json", hdrs.AUTHORIZATION: f"Bearer {token}", } races = context["races"] race_to_be_updated_id = races[-1] # we...
5,310,360
def _docker_registry_htpasswd( *, docker_registry_password_list: List[str], docker_registry_username_list: List[str], pytestconfig: "_pytest.config.Config", scale_factor: int, tmp_path_factory: TempPathFactory, ) -> Generator[List[Path], None, None]: """Provides the location of the htpasswd ...
5,310,361
def delete_volumes(repository_name, branch_name): """ Trigger lambda function that deletes EBS volumes. :param repository_name: Full repository name. :param branch_name: Branch name that is deleted. :return: Number of EBS volumes that are deleted successfully, number of EBS volumes that are not dele...
5,310,362
def train_main(args_opt): """main code for train refinedet""" rank = 0 device_num = 1 # config with args config = get_config(args_opt.using_mode, args_opt.dataset) # run mode config if args_opt.debug == "1" or args_opt.debug == "3": network_mode = context.PYNATIVE_MODE else: ...
5,310,363
def load_user(user_id): """根据session中的user_id获取User对象""" from albumy.models import User user = User.query.get(int(user_id)) return user
5,310,364
def load_saved_recipes(filename): """ Internal method for reading contens of given file. """ contents = [] try: # Read file line by line, recipe by recipe with open(filename, 'r') as recipes_file: contents = recipes_file.readlines() return contents ...
5,310,365
def get_range(arr, refarea): """ determine plot scale range """ auto_crange: float = 99.8 refvalue = np.nanmean(arr[refarea[0]:refarea[1], refarea[2]:refarea[3]]) # reference values if str(refvalue) == 'nan': refvalue = 0 dmin_auto = np.nanpercentile((tscuml[-1, :, :]), 100 - auto_cr...
5,310,366
def cvSetMouseCallback(window_name, on_mouse, param=None): """void cvSetMouseCallback( const char* window_name, CvMouseCallback on_mouse, void* param=NULL ) Assigns callback for mouse events """ if param is None or isinstance(param, c_void_p): orig_param = None else: orig_param = p...
5,310,367
def update_workmail(message_id, bucket, content, key): """ Uploads the updated message to an S3 bucket in your account and then updates it at WorkMail via PutRawMessageContent API. Reference: https://docs.aws.amazon.com/workmail/latest/adminguide/update-with-lambda.html Parameters ---------- ...
5,310,368
def label_repo( source: str = typer.Argument(CWD), input: str = typer.Option('', '-i', '--input'), output: str = typer.Option('', '-o', '--output'), template: str = typer.Option('', '-t', '--template'), ) -> int: """ Labels the local data (no template handling yet). """ repo_root = input...
5,310,369
def get_longest_word_trie_ds(words: list[str]) -> str: """Returns the longest word character composable from other words in input array Args: words: array of strings words representing an English Dictionary Returns: the longest word in words that can be built one character at a time by ...
5,310,370
def occnet_decoder(embedding, samples, apply_sigmoid, model_config): """Computes the OccNet output for the input embedding and its sample batch. Args: embedding: Tensor with shape [batch_size, shape_embedding_length]. samples: Tensor with shape [batch_size, sample_count, 3]. apply_sigmoid: Boolean. Whe...
5,310,371
def test_delete_mtext_with_linked_columns_from_entitydb(doc): """Delete MTEXT by EntityDB.delete_entity().""" db = doc.entitydb mtext = new_mtext_with_linked_columns(3) doc.entitydb.add(mtext) count = len(db) doc.entitydb.delete_entity(mtext) db.purge() assert len(db) == count - 3, "shou...
5,310,372
async def async_combine_middlewares( middlewares: Sequence[Middleware], web3: 'Web3', provider_request_fn: Callable[[RPCEndpoint, Any], Any], ) -> Callable[..., RPCResponse]: """ Returns a callable function which will call the provider.provider_request function wrapped with all of the middleware...
5,310,373
def embedding_attention_seq2seq_context(encoder_inputs, decoder_inputs, cell, num_encoder_symbols, num_decoder_symbols, embedding_size, num_heads=1, output_projection=None, ...
5,310,374
def is_positive_integer(value: str) -> int: """ Helper function for argparse. Raise an exception if value is not a positive integer. """ int_value = int(value) if int_value <= 0: raise argparse.ArgumentTypeError(f"{value} is not a positive integer") return int_value
5,310,375
def _create_image(dirs, class_info, params, count, output_dir): """Creates a dataset image at the desired directory. Returns bbox cache for creating annotations.""" # open the map and create a copy of it as a new image background_image = Image.open(choice(glob.glob(dirs['maps']+'.png'))) new_image = bac...
5,310,376
def compute_predictions_for_a_single_pipeline(p,df_X): """ This function finds predictions for a single pipeline (it is assumed that this is already the best model) Parameters ---------- p : prediction_class object df_X: DataFrame Input dataframe with possible all the original attr...
5,310,377
def min_edit_distance( source: Sequence[T], target: Sequence[T], ins_cost: Callable[..., int] = lambda _x: 1, del_cost: Callable[..., int] = lambda _x: 1, sub_cost: Callable[..., int] = lambda x, y: 0 if x == y else 1) -> int: """Calculates the minimum edit distance between two seque...
5,310,378
def print_bb_result(phase_ts): """ Print BigBench result :param phase_ts: dict that keys are BigBench phase and values are elapsed time :return: None """ df = pd.DataFrame(index=phase_ts.keys(), columns=('EpochStartTime', 'EpochEndTime', 'ElapsedTime')) for key, value in phase_ts.items(): ...
5,310,379
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Home Connect light.""" def get_entities(): """Get a list of entities.""" entities = [] hc_api = hass.data[DOMAIN][config_entry.entry_id] for device_dict in hc_api.devices: entity_dicts...
5,310,380
def combine(batch, i): """ Combines the vectors for a specific type of sequence and removes extra padding Args: batch: list i: int indicates the type of sequence (4, 5, 6) --> (passage, query, qa_answer) Returns: vectors: 2d long tensor [bs x max_len] """ vectors = torch.cat([example[i].unsqueeze(...
5,310,381
def GetNetworkConfig(has_external_ip, network): """Helper method to create a network config.""" network_interfaces = { 'network': network } if has_external_ip: network_interfaces['accessConfigs'] = [{ 'name': 'external-nat', 'type': 'ONE_TO_ONE_NAT' }] return network_interfaces
5,310,382
def base_federated_role( construct, resource_name: str, federated_resource: str, assume_role_action: str, conditions: dict, actions: list, resources: list, ): """ Function that generates an IAM Federated Role with a Policy. :param construct: Custom construct that will use this fu...
5,310,383
def zeros(a): """ Return the number of cleared bits in the sequence. >>> assert zeros([0, 0]) == 2 >>> assert zeros([0, 1]) == 1 >>> assert zeros([1, 0]) == 1 >>> assert zeros([1, 1]) == 0 >>> assert zeros([1, 1, 1, 0, 1]) == 1 >>> assert zeros([0, 1, 0, 0, 0]) == 4 """ return s...
5,310,384
def test_commit_in_last_year_no(monkeypatch): """ 11. Has there been a commit in the last year? """ headers = {} def mock_get(*args, **kwargs): return MockResponseCommitsNo() today = datetime.now() test_date = datetime.strptime(BAD_DATE_Z, "%Y-%m-%dT%H:%M:%SZ") days = (today - ...
5,310,385
def load_response_function(f, fstar=19.09e-3): """Load in LISA response function from file Load response function and interpolate values for a range of frequencies. Adapted from https://github.com/eXtremeGravityInstitute/LISA_Sensitivity to use binary files instead of text. See Robson+19 for more detai...
5,310,386
def edit(request): """ Save profile changes. Args: request (HttpRequest): Request with user profile data passed with the `GET` method. Returns: An `HttpResponse` with search results. """ if request.method == 'POST': # Apparently, `<form> .__ call __ ()` can...
5,310,387
def _make_training_input_fn(transformed_dataset): """训练数据处理""" def input_fn(): x, y = [], [] s = set() for tdt in transformed_dataset: x.append(tdt["x"].tolist()) s.add(len(tdt["x"].tolist())) y.append(tdt["y"]) print(list(s)) x, y = np...
5,310,388
def add_mass_profile(profile, chk_h5py): """Calculate enclosed mass profile and add to profile table parameters ---------- profile : xr.Dataset table as returned by extract_profile() chk_h5py : h5py.File """ if ('r' not in profile) or ('dens' not in profile): raise ValueErro...
5,310,389
def _do_select_for_plugin_api(params): """A version of select_for_plugin_api which accepts indirect products.""" if not params: fail("Empty select_for_plugin_api") expanded_params = dict(**params) # Expand all indirect plugin_apis to point to their # corresponding direct plugin_api. # ...
5,310,390
def escape_special_char(string): """ Is called on all paths to remove all special characters but it's not good. Should be moved in core Should be called only in get_wrapper_path and unescape_special_char in get_entry and in script += 'menu_click... in menu_click as it's already done ...
5,310,391
def search_product_with_application_id(app_id): """ Searches for Products based on application id association :param app_id: application id that is being used in products :return : True or False Indicates Success (Product Found) or Failure (Product Not Found) and ProductID """ api_url = get_pro...
5,310,392
def bcast_param( inp: Union[Buffer, Parameter], key: str, nr_ranks: Optional[int] = None, rank: Optional[int] = None, root: Optional[int] = 0, ) -> None: """Broadcast parameters among devices :param inp: input Buffer or Parameter to be synchronized :param key: unique identifier for coll...
5,310,393
def jinc(x, normalize=True): """Evaluate the jinc function in the input corodinate ``x`` Parameters ---------- x : a single point or an ndarray the input corodinate normalize : bool, optional if ``True`` (default), the normalized jinc (``jinc(0)=1``) is returned Returns...
5,310,394
def fp_search_rglob(spt_root="../", st_rglob='*.py', ls_srt_subfolders=None, verbose=False, ): """Searches for files with search string in a list of folders Parameters ---------- spt_root : string root folder to sea...
5,310,395
def decode_atbash(string, abc=None): """ Decodes a string with the classic atbash ciphering method :param string: :param abc: :return decoded string: """ if abc is None: abc = abc_en.copy() elif type(abc) == list: abc = abc.copy() elif type(abc) != tuple: retu...
5,310,396
def affine_subbasis(mode, dim=3, sub=None, dtype='float64'): """Generate a basis set for the algebra of some (Lie) group of matrices. The basis is returned in homogeneous coordinates, even if the group required does not require translations. To extract the linear part of the basis: lin = basis[:-1, :-1...
5,310,397
def transition_layer(x, nb_channels, dropout_rate=None, compression=1.0, weight_decay=1e-4): """ Creates a transition layer between dense blocks as transition, which do convolution and pooling. Works as downsampling. """ x = BatchNormalization(gamma_regularizer=l2(weight_decay), beta_regularize...
5,310,398
def mobilenet_v2(pretrained=False, progress=True, **kwargs): """ Constructs a MobileNetV2 architecture from `"MobileNetV2: Inverted Residuals and Linear Bottlenecks" <https://arxiv.org/abs/1801.04381>`_. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (...
5,310,399