content
stringlengths
22
815k
id
int64
0
4.91M
def index(metadata_context: BaseContext = Provide[ApplicationContainer.context_factory]): """Handler for base level URI for the features endpoint. Supports GET and POST methods for interacting.""" if request.method == constants.HTTP_GET: with metadata_context.get_session() as session: fe...
59,600
def select_area(ds, lon, lat, g_step=0.25): """ Select data for given location or rectangular area from dataset. In case data for a single location is requested, the nearest data point for which weather data is given is returned. Parameters ----------- ds : xarray.Dataset Dataset w...
59,601
def spatial_clustering(mask, algorithm="DBSCAN", min_cluster_size=5, max_distance=None): """Counts and segments portions of an image based on distance between two pixels. Masks showing all clusters, plus masks of individual clusters, are returned. Inputs: mask = Mask/binary image to segment...
59,602
def get_ordered_dataset(file_pattern, blocks_only=True, shuffle=True): """Given a file pattern,return the dataset contained. If specified, shuffle the dataset group-wise. :param blocks_only: whether to only use records with 'is_extracted_block' == True :type blocks_only: bool :param file_pattern: t...
59,603
def test_minor_radius(tokamak_args_dict): """Checks that TokamakSource creation only accepts valid minor radius""" # Set major radius, pedestal radius, and shafranov factor to nice values tokamak_args_dict["major_radius"] = 10 tokamak_args_dict["pedestal_radius"] = 0.1 tokamak_args_dict["shafranov_f...
59,604
def build_vxlan_header(encapsulation_header, ethernet_header): """ Build NSH header with underlying ethernet header :param encapsulation_header: VXLAN or GRE NSH header :type encapsulation_header: `:class:nsh.common.VXLANGPE|GREHEADER` :param base_header: base NSH header :type base_header: `:cl...
59,605
def generate_gallery(db: BeautifulSoup, c=g_config): """ Examples of filters: - date >= 2020 ; date <= 2021 -- to filter specific years - format = PNG ; bytes > 100000 -- to filter by format and disk-size - width > 5000 ; height > 4000 -- to filter by image width & height - make-model ~~ Sony...
59,606
def create_blog_article_thumbnails(image_id: str): """Take a Blog model and create thumbnails for it.""" create_thumbnails(pk=image_id, model=BlogArticle, size_set="blog")
59,607
def _new_obj(original_function): """Decorator to deepcopy unaltered states into new object Parameters ---------- original_function : callable Callable must return None or a Mapping with some or all of _state_attrs defined. Returns ------- new_function : callable New...
59,608
def Aggregate_median_SABV(rnaseq): """Compute median TPM by gene+tissue+sex.""" logging.info("=== Aggregate_median_SABV:") logging.info(f"Aggregate_median_SABV IN: nrows = {rnaseq.shape[0]}, cols: {str(rnaseq.columns.tolist())}") rnaseq = rnaseq[["ENSG", "SMTSD", "SEX", "TPM"]].groupby(by=["ENSG", "SMTSD", "SEX...
59,609
def is_similar_except_in_shape( definition_or_instance_1: Dict[str, Any], definition_or_instance_2: Dict[str, Any], only_x_dimension: bool = False ) -> bool: """Return whether the two given objects are similar in color (material category) and size (dimensions) but not shape (type).""" size_list ...
59,610
def scandir(dir_path, suffix=None, recursive=False, full_path=False): """ From BasicSR: https://github.com/xinntao/BasicSR Scan a directory to find the interested files. Args: dir_path (str): Path of the directory. suffix (str | tuple(str), optional): File suffix that we are ...
59,611
def simpleapi(): """Cross-Microservice call""" url = getservice(APP.node, "simple-api") key = requests.get(url + "/simple-api/version", timeout=1) return (key.text, 200)
59,612
def mac_address(name, value): """Validate that the value represents a MAC address :param name: Name of the argument :param value: A string value representing a MAC address :returns: The value as a normalized MAC address, or None if value is None :raises: InvalidParameterValue if the value is not a ...
59,613
def test_get_encryption_materials_committing_algorithm_policy_forbids(): """Tests that a Default Crypto Materials Manager request with policy FORBID_ENCRYPT_ALLOW_DECRYPT cannot encrypt using an algorithm that provides commitment.""" mock_alg = MagicMock(__class__=Algorithm) mock_alg.is_committing.retur...
59,614
def total_dist_from_point(data: CachingDataStructure, start_point: tuple, max_prop_level: int = INF) -> tuple: """ For some CachingDataType, it calculates the distance in linear space for all different propagation levels. Returns a tuple of three arrays; (1) an array of propaga...
59,615
def compute_curve(labels, predictions, num_thresholds=None, weights=None): """ Compute precision-recall curve data by labels and predictions. Args: labels (numpy.ndarray or list): Binary labels for each element. predictions (numpy.ndarray or list): The probability that an element be ...
59,616
def test_normalize_host_result_is_expected(): """Assert we got expected results from the normalize_host function.""" for url, expected in EXPECTED_DATA.items(): result = normalize_host(url) assert result == expected, url
59,617
def read_database(): """ Deserialize the database and read into a list of sets for easier selection and O(1) complexity. Initialize the multiprocessing to target the main function with cpu_count() concurrent processes. """ database = [set() for _ in range(4)] count = len(os.listdir(DATABASE)) half = count // ...
59,618
def test_rest_api_failing_objects_pagination(auth_client): """ test that failing objects are paginated """ page_size = FailingObjectPagination.page_size TestModel.objects.generate(failing=page_size+1) ModelValidationRunner(TestModel, method_names=["check_foobar"]).run() url = reverse("admin:failing...
59,619
def _split_series(df, series_id, target, by='quantiles', cuts=5, split_col='Cluster'): """ Split series into clusters by rank or quantile of average target value by: str Rank or quantiles cuts: int Number of clusters split_col: str Name of new column Returns: -----...
59,620
def extract_data_with_labels(npy_file_path, subject_labels, config): """Extracts train_val and test data and subjects from npy and csv file Args: config (Omegaconf dict): contains configuration parameters Returns (subjects as dataframe, data as numpy array): train_val_subjects, train_val_da...
59,621
def content_disposition_filename(filename): """ Sanitize a file name to be used in the Content-Disposition HTTP header. Even if the standard is quite permissive in terms of characters, there are a lot of edge cases that are not supported by different browsers. See http://greenbytes.de/tech/t...
59,622
def new_query(event, *args): """Add new query session <kind of deprecated> Args: url: review/{review_id}/query body: "search" <search dict (wrapper/input_format.py)> Returns: { "review": review object, "new_query_id": new_query_id ...
59,623
def test_stochastic_rsi_strategy(df): """Checks stochastic RSI strategy calculates correctly.""" df_with_allocations = allocations.stochastic_RSI_strategy(df, 14, max_investment) df_with_signals = stochastic_relative_strength_index(df, 14) over_valued = df_with_signals["signal"] >= 0.8 under_valued...
59,624
def supervisor_command(command): """Run a supervisorctl command.""" sudo(u'supervisorctl %s' % command)
59,625
def GraphHistograms( histFiles, outFile = None, xlabel = '', ylabel = '', title = '', labels = (), colors = 'brcmygkbrcmygkbrcmygkbrcmygk', relWidth = 0.4, xbound = None, ybound = None, coarsenBy = None, sfx = '', ticksCoarsen = 1, log ...
59,626
def update(gen, test: dict, context: dict, event): """ :param gen: 一个generator对象 :param test: 传入的本次测试配置(来自config.yaml) :param context: 测试运行时的上下文,包括当前空闲线程、时间等信息 :param event: 事件,通常是一个op :return: gen2: 通过该次调用传入的generator的状态得到了更新,返回更新后的generator """ if gen is None: return None ...
59,627
def test_azure_storage_get_blob_command(requests_mock): """ Scenario: Retrieve Blob from Container. Given: - User has provided valid credentials. When: - azure-storage-container-blob-get called. Then: - Ensure XSOAR File output. """ from AzureStorageContainer import Client, ge...
59,628
def get_rig_list(path): """ Recursively searches for rig types, and returns a list. """ rigs = [] MODULE_DIR = os.path.dirname(__file__) RIG_DIR_ABS = os.path.join(MODULE_DIR, utils.RIG_DIR) SEARCH_DIR_ABS = os.path.join(RIG_DIR_ABS, path) files = os.listdir(SEARCH_DIR_ABS) files.sort() ...
59,629
def get_time_at(time_in=None, time_at=None, out_fmt="%Y-%m-%dT%H:%M:%S"): """ Return the time in human readable format for a future event that may occur in ``time_in`` time, or at ``time_at``. """ dt = get_timestamp_at(time_in=time_in, time_at=time_at) return time.strftime(out_fmt, time.localtim...
59,630
def plot_alignment(alignment, path): """ Plot an attention layer's alignment for a sentence. alignment: shape(T_dec, T_enc). """ plt.figure() plt.imshow(alignment) plt.colorbar() plt.xlabel('Encoder timestep') plt.ylabel('Decoder timestep') plt.savefig(path) plt.close()
59,631
def synchronized(lock): """ Synchronization decorator. """ def wrap(f): def new_function(*args, **kw): lock.acquire() try: return f(*args, **kw) finally: lock.release() return new_function return wrap
59,632
def end_debug_session(): """ End debug session """ terminal.display("API command: End debug session\n") debugger.end_debug_session()
59,633
def make_snippet(snippets, location): """Makes a colored html snippet.""" output = "<br>".join(sentence.replace( location, f'<i style="background-color: yellow;">{location}</i>') for sentence in snippets) return output
59,634
def test_exception_handler(): """ Ensure exceptions are provided to the handler if one exists :raises AssertionError :return void """ def work(item): raise Exception def handler(e): pass assert not bool(list(pipe.Pipe( exception_handler = handler ).run(rang...
59,635
def validate_iam_group_names(group_names): """Since the IAM group names are passed into the CLI as arguments, this will validate them to ensure that these group names exist and were typed correctly.""" client = boto3.client('iam') for group_name in group_names: logger.info(f"Validating IAM g...
59,636
def main(): """Main function""" print("\nGreedy Best First Search\n----------------------\n") print('(Your now at) :', end=' ') source = input().strip() print('(Where to go) :', end=' ') goal = input().strip() if source not in Heuristic_value_graph or goal not in Heuristic_value...
59,637
def test_capture_pcap(serializer, api, tx_port, rx_port): """Demonstrates how to start capture and get capture results """ config = Config(ports=[tx_port, rx_port]) # configure capture filter = MacAddressFilter(mac='source', filter='000000000000') config.captures.append( Capture(name='r...
59,638
def read_data(filenames, mode): """ The main function to read all the back calculated files Parameters ---------- filenames: dict This parameter is a dictionary of properties with their relative path to the data file. mode: str This parameter must be one of the following: ...
59,639
def is_identity(mat, eps=None): """Checks if a matrix is an identity matrix. If the input is not even square, ``False`` is returned. Args: mat (numpy.ndarray): Input matrix. eps (float, optional): Numerical tolerance for equality. ``None`` means ``np.finfo(mat.dtype).eps``. ...
59,640
def get_pem_entries(glob_path): """ Returns a dict containing PEM entries in files matching a glob glob_path: A path to certificates to be read and returned. CLI Example: .. code-block:: bash salt '*' x509.get_pem_entries "/etc/pki/*.crt" """ ret = {} for path in glo...
59,641
def connect_to_db_via_ssh(ssh_info, db_info): """ Connects to a remote PostgreSQL db, via SSH tunnel. Args: ssh_info (obj): All ssh connection info. db_info (obj): All db related connection info. Returns: :class:`psycopg2.extensions.connection`: Live connection suitable for que...
59,642
def kid_2(): """Return a second JWT key ID to use for tests.""" return "test-keypair-2"
59,643
def list_engine(config): """This module will list engine from pool""" globals.initialize(config.debug, config.verbose, script_dir) if config.verbose or config.debug: click.echo("Verbose mode enabled") try: mskai = masking(config, noparam="noparam") mskai.list_engine() ...
59,644
def fold_chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield lst[i:i + n]
59,645
def get_world_size(): """ Get the size of the world. """ if 'WORLD_SIZE' in os.environ: return int(os.environ['WORLD_SIZE']) else: if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size()
59,646
def cosine_sim(x1, x2, dim=-1, eps=1e-8): """Returns cosine similarity between x1 and x2, computed along dim.""" w12 = torch.sum(x1 * x2, dim) w1 = torch.norm(x1, 2, dim) w2 = torch.norm(x2, 2, dim) return (w12 / (w1 * w2).clamp(min=eps)).squeeze()
59,647
def overlap(b4_reg, b7_reg, sep): """ function to find ds9 ellipse regions that match or overlap between band 4 and band 7 """ # define some other little functions def match_function(c, c_array, sep): """ c would be a single band 4 dust region c_array would be array of the band 7 regions """ # find wher...
59,648
def tile_array_2d(array: np.ndarray, tile_size: int, channels_first: Optional[bool] = True, **pad_kwargs: Any) -> Tuple[np.ndarray, np.ndarray]: """Split an image array into square non-overlapping tiles. The array will be padded symmetrically if its dimensions are not exact multiples of `tile...
59,649
def get_filenames(ruleset_db, rule): """returns a list of all filenames for a rule in a ruleset""" from src.praxxis.sqlite import connection conn = connection.create_connection(ruleset_db) cur = conn.cursor() list_filenames = 'SELECT Filename FROM "Filenames" WHERE Rule = ?' cur.execute(l...
59,650
def toy_features(): """ Generate a sample feature dataframe with one column that isn't a feature. """ feat = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9], "D": ["a", "b", "c"]}) return (feat, feat.loc[:, ...
59,651
def test_apply_to_lhs_print_unchanged(eq1_eq2): """Test that "apply_to_lhs" always prints the lhs, even if it did not change""" eq1, _ = eq1_eq2 eq = eq1.apply_to_lhs(sympy.simplify) assert str(eq) == '2*x - y = 1 (I)\n2*x - y = 1'
59,652
def cube_px_resampling(array, scale, imlib='opencv', interpolation='bicubic', scale_y=None, scale_x=None): """ Wrapper of frame_px_resample() for resampling the frames of a cube with a single scale. Useful when we need to upsample (upsacaling) or downsample (pixel binning) a set of f...
59,653
def tint_raw(img, color, opacity=255): """Tint the image.""" if isinstance(img, str): try: img = sublime.load_binary_resource(img) except Exception: _log('Could not open binary file!') _debug(traceback.format_exc(), ERROR) return '' return ima...
59,654
def move_items_back(garbages): """ Moves the items/garbage backwards according to the speed the background is moving. Args: garbages(list): A list containing the garbage rects Returns: garbages(list): A list containing the garbage rects """ for garbage_rect in garbages: # Loop...
59,655
def seed_rngs(seed: int, ctx: Optional[Union['mx.Context', List['mx.Context']]] = None) -> None: # type: ignore """ Seed the random number generators (Python, Numpy and MXNet). :param seed: The random seed. :param ctx: Random number generators in MXNet are device specific. If None, MXNet wi...
59,656
def optimize(inputs, output, sizes): """ Produces an optimization path similar to the greedy strategy :func:`opt_einsum.paths.greedy`. This optimizer is cheaper and less accurate than the default ``opt_einsum`` optimizer. :param list inputs: A list of input shapes. These can be strings or sets or ...
59,657
def variation(inlist:List(float))->float: """ Returns the coefficient of variation, as defined in CRC Standard Probability and Statistics, p.6. Usage: lvariation(inlist) """ return 100.0*variability.samplestdev(inlist)/float(central_tendency.mean(inlist))
59,658
def process_zdr_column(procstatus, dscfg, radar_list=None): """ Detects ZDR columns Parameters ---------- procstatus : int Processing status: 0 initializing, 1 processing volume, 2 post-processing dscfg : dictionary of dictionaries data set configuration. Accepted Config...
59,659
def _mask_pattern(dirty: str): """ Masks out known sensitive data from string. Parameters ---------- dirty : str Input that may contain sensitive information. Returns ------- str Output with any known sensitive information masked out. """ # DB credentials as found...
59,660
def cleanString(currentString): """ Remove extra spaces and final punctuation from string. """ cleanstring = currentString.strip() cleanerString = removePunctuationField(cleanstring) return cleanerString
59,661
def writePhaseNLL(phases, evekey, NLLoc_dir, useP=True, useS=True): """ Write a y2k complient phase file used by hypoinverse 2000, format defined on page 113 of the manual for version 1.39 Parameters --------- phases : pandas dataframe or path to csv Phase input from AssociatePhases scri...
59,662
def train( images_path: str, texts_path: str, train_imgs_file_path: str, val_imgs_file_path: str, epochs: int, recall_at: int, batch_size: int, prefetch_size: int, save_model_path: str, log_model_path: str, learning_rate: float, weight_decay: float, joint_space: int, ...
59,663
def getFilename_fromCd(cd): """ Get filename from content-disposition """ if not cd: return None fname = re.findall("filename=(.+)", cd) if len(fname) == 0: return None return fname[0]
59,664
def redirect_view(request, url): """ Redirect all requests that come here to an API call with a view parameter. """ dest = '/api/%.1f/%s' % (legacy_api.CURRENT_VERSION, urllib.quote(url.encode('utf-8'))) dest = get_url_prefix().fix(dest) return HttpResponsePermanent...
59,665
def set_compartment(name=None, **kwargs): """Sets properties of the named compartment :param name: the name of the compartment (or a substring of the name) :type name: str :param kwargs: optional arguments - | `initial_value` or `initial_size`: to set the initial size of the compartment ...
59,666
def compressToDays(cursor, dayList): """ Args: (mysql obj): cur, mysql cursor object (list): daysList, list of days to compress from hourly Desc: Automatically compresses hours per day into single day point for rid,logdate,location,data_type """ for day in dayList...
59,667
def arch_matches(arch, alias): """ Check if given arch `arch` matches the other arch `alias`. This is most useful for the complex any-* rules. """ if arch == alias: return True if arch == 'all' or arch == 'source': # These pseudo-arches does not match any wildcards or aliases ...
59,668
def calc_m_q_inv_m(m, q, flag_m: bool = False, flag_q: bool = False): """ q is quadratic form q_11, q_22, q_33, q_12, q_13, q_23 m is matrix m_11, m_12, m_13, m_21, m_22, m_23, m_31, m_32, m_33 Output is matrix o """ m_11, m_12, m_13 = m[0], m[1], m[2] m_21, m_22, m_23 = m[3], m[4], m...
59,669
def divisors(n): """ Returns a list of all positive integer divisors of the nonzero integer n. INPUT: - ``n`` - the element EXAMPLES:: sage: divisors(-3) [1, 3] sage: divisors(6) [1, 2, 3, 6] sage: divisors(28) [1, 2, 4, 7, 14, 28] s...
59,670
def list_to_hash(lst): """Convert a flat list of key value pairs to a hash""" return {lst[i]: lst[i+1] for i in range(0, len(lst), 2)};
59,671
def upsert_account(addr, account, success_ctr, retry_ctr): """Runs upsert operation.""" client = helper.create_client(addr) client.login("groot", "password") query = """{{ acct(func:eq(first, "{first}")) @filter(eq(last, "{last}") AND eq(age, {age})) {{ uid }} }}""".forma...
59,672
def get_multiparm_instance_indices( parm: Union[hou.Parm, hou.ParmTuple], instance_index: bool = False ) -> Tuple[int, ...]: """Get the multiparm instance indices for this parameter tuple. If this parameter tuple is part of a multiparm, then its index in the multiparm array will be returned as a tuple....
59,673
def register_parquet(): """ Register Parquet with Unified I/O. """ from astropy.io import registry as io_registry from astropy.table import Table io_registry.register_reader('parquet', Table, read_table_parquet) io_registry.register_writer('parquet', Table, write_table_parquet) io_regis...
59,674
def two_point_template(config): """Creates a template SACC object with tracers and statistics Parameters: ---------- config : dict The dictinary containt the relevant two_point section of the config Returns: ------- sacc : sacc object Sacc objects with appropriate tracers a...
59,675
def first_time(series, value, window=None): """:func:`aggfunc` to: - Return the first index where the series == value - If no such index is found +inf is returned :param series: Input Time Series data :type series: :mod:`pandas.Series` :param window: A tuple indicating a time win...
59,676
def test_handle_program_no_entries(): """ We should do the right thing if there are no entries for a given program. """ program = 'cp' test_config = _create_config() with patch( 'eg.util.get_resolved_program', return_value=program ) as mock_resolve_program: with patc...
59,677
def post_to_slack(config, message): """Post a message to the the slack channel specified in the configuration file.""" try: key = config.get('Slack', 'key') channel = config.get('Slack', 'channel') from slacker import Slacker slack = Slacker(key) slack.chat.post_message(...
59,678
def prepare_filter_triples( mapped_triples: MappedTriples, additional_filter_triples: Union[None, MappedTriples, List[MappedTriples]] = None, ) -> MappedTriples: """Prepare the filter triples from the evaluation triples, and additional filter triples.""" if additional_filter_triples is None: log...
59,679
def create(): """ Progress can be added to any/all goal(s) displayed. """ goals = fetch_goals() if request.method == "POST": data_id = request.form.getlist("id") data_progress = request.form.getlist("progress") data_quality = request.form.getlist("grade") data = {...
59,680
def load_bikeshare(data_path=FIXTURES): """ Downloads the 'bikeshare' dataset, saving it to the output path specified and returns the data. """ # name of the dataset name = 'bikeshare' data = load_numpy(name, data_path=data_path) return data
59,681
def PrintAndAssertOutput(cc): """ /* * Print sampled values of current cc */ """ from nose.tools import assert_almost_equal jy = 0 jx = 0 print "\nAt bottom left:" #/* Print out lines with up to 6 values per line */ for _is in range(NUM_SPECIES): p...
59,682
def test_cleanup_failed_err(install_mockery, tmpdir, monkeypatch, capsys): """Test _cleanup_failed exception path.""" msg = 'Fake release_write exception' def _raise_except(lock): raise RuntimeError(msg) const_arg = installer_args(['trivial-install-test-package'], {}) installer = create_in...
59,683
def svn_wc_add_lock(*args): """svn_wc_add_lock(char const * path, svn_lock_t lock, svn_wc_adm_access_t * adm_access, apr_pool_t pool) -> svn_error_t""" return _wc.svn_wc_add_lock(*args)
59,684
def test_calculator_subtract(clear_history): """Testing the subtract method of the calculator""" assert Calculator.subtract_number((1, 2)) == -3
59,685
def plot_terms_body(topic, data, minimum_frequency): """ The np.aranage attribute is to understand how to best and programmatically plot the data. Intervals are determined by the counts within the dictionary. The user does not need to predefine the graph. Instead, the second line takes the freque...
59,686
def analyze_events(paths_to_event_files, experiment_root_dir, do_finegrainedness_analysis, do_imbalance_analysis, force_recompute): """Analyzes each event file and stores the .pklz in the corresponding dir.""" # Aggregate stats across all event files and write (the summarized ...
59,687
def test_att_p022_att_p022_v(mode, save_output, output_format): """ TEST :Syntax Checking for Attribute Declaration (form) : use=absent, default="37" (may appear once, may have any value), instant xml value=37 """ assert_bindings( schema="msData/attribute/attP022.xsd", instance="...
59,688
def contains_non_ascii_unicode(s): """Determine whether the Unicode string 's' contains non-ASCII code-points.""" # Surely there must be a better way to do this? There's nothing I can see in # the stdlib 'unicodedata' module: # http://docs.python.org/library/unicodedata.html # # Note that list comprehens...
59,689
def build_profile_information(user): """ Returns a dictionary containing information relevant to an user's profile. Override this function to add additional information to an user's profile. """ context = {} context['user'] = user up_votes = Vote.objects.filter(user = use...
59,690
def __remove_duplicate_chars(string_input, string_replace): """ Remove duplicate chars from a string. """ while (string_replace * 2) in string_input: string_input = \ string_input.replace((string_replace * 2), string_replace) return string_input
59,691
def generate_message(username, pr_list): """Generates message using the template provided in PENDING_REVIEW_NOTIFICATION_TEMPLATE.md file. """ template_path = '.github/PENDING_REVIEW_NOTIFICATION_TEMPLATE.md' if not os.path.exists(template_path): raise Exception( 'Please add a te...
59,692
def test_ecomap(): """ test mappings between GAF codes and ECO """ m = EcoMap() assert m.coderef_to_ecoclass('IEA','GO_REF:0000002') == 'ECO:0000256' assert m.coderef_to_ecoclass('IEA') == 'ECO:0000501' assert m.coderef_to_ecoclass('IEA','FAKE:ID') == 'ECO:0000501' assert m.ecoclass_to_c...
59,693
def clean_data(df): """Split the categories column to 36 individual columns and convert their values to 0 / 1. Drop the original categories column. Drop duplicated rows. Args: df: the dataset Returns: DataFrame: the cleaned dataset """ # split categories into separate c...
59,694
def format_birthday_for_database(p_birthday_of_contact_month, p_birthday_of_contact_day, p_birthday_of_contact_year): """Takes an input of contact's birthday month, day, and year and creates a string to insert into the contacts database.""" formated_birthday_string = p_birthday_of_contact_month + "/" + p_birthd...
59,695
def pow_json_serializer(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): #serial = obj.isoformat() serial = obj.strftime(twittercomments.config.myapp["date_format"]) return serial if isinstance(obj, uuid.UUID): retur...
59,696
def scale_poscar(path_poscar,scale=(1,1,1),tol=1e-2): """Create larger/smaller cell from a given POSCAR. - **Parameters** - path_poscar: Path/to/POSCAR or `poscar` data object. - scale: Tuple of three values along (a,b,c) vectors. int or float values. If number of sites are not as expected in ou...
59,697
def device_management_submenu(dev, pdmssp=False): """ Method - Show Device Information Menu INPUTS: dev as object OUTPUT: none """ loop = True menu.clear() while loop: print("Device Management Menu") print("======================") print("1. Import from cfg (x...
59,698
def normal_distribution(x: float) -> float: """ 標準正規分布 f(x) = (1/sqrt(2pi))exp(-x^2/2) """ # 係数 coefficient = 1 / math.sqrt(2 * math.pi) # 指数 exponent = math.exp(-(x ** 2) / 2) # 標準正規分布 return coefficient * exponent
59,699