content
stringlengths
22
815k
id
int64
0
4.91M
def password_validate(password): """It validates password using regular expression :param password: contains the users password :returns: Boolean :raises: ValidationError """ if re.match( r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$", password, ): ...
40,700
def get_emr_cluster_status(cluster_id: str, detail: bool = False): """ Provides cluster-level details including status, cluster_id, cluster_name and so on. Args: cluster_id: string, EMR cluster id detail: bool, provided additional detail about cluster like ec2 attributes Returns: ...
40,701
def main(): """\ Performs a natural sort on entries given on the command-line. A natural sort sorts numerically then alphabetically, and will sort by numbers in the middle of an entry. >>> import sys >>> sys.argv[1:] = ['num-2', 'num-6', 'num-1'] >>> main() num-6 ...
40,702
def get_keypair() -> KeyPairInfo: """Returns current keypair (ec2.KeyPairInfo) https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#keypairinfo """ return get_keypair_dict()[get_keypair_name()]
40,703
def char_vectorizer(char, custom_alphabet=False): """ Vectorize given nucleotide character. Convert to uppercase before vectorizing. >>> char_vectorizer("C") [0, 1, 0, 0] >>> char_vectorizer("g") [0, 0, 1, 0] >>> char_vectorizer("M", ['E', 'H', 'I', 'M', 'S']) [0...
40,704
def test_6(p, d): """ Checks results against different version of the quadratic gradient using for loop. """ lambda_1 = 1 lambda_2 = 10 store_A = np.zeros((p, d, d)) store_x0 = np.zeros((p, d)) store_rotation = np.zeros((p, d, d)) for i in range(p): diag_vals = np.zeros(d...
40,705
def test_get_validator_ambiguous_parameter_pandas_engine( data_context_with_datasource_pandas_engine, test_df_pandas ): """ What does this test and why? get_batch_list() requires batch_request to be passed in a named parameter. This test passes in a batch_request as an unnamed parameter, which will...
40,706
def orbit_from_name(name): """Return :py:class:`~poliastro.twobody.orbit.Orbit` given a name. Retrieve info from JPL DASTCOM5 database. Parameters ---------- name : str NEO name. Returns ------- orbit : list (~poliastro.twobody.orbit.Orbit) NEO orbits. """ rec...
40,707
def make_snowflake(timestamp_ms, datacenter_id, worker_id, sequence_id, twepoch=twepoch): """generate a twitter-snowflake id, based on https://github.com/twitter/snowflake/blob/master/src/main/scala/com/twitter/service/snowflake/IdWorker.scala :param: timestamp_ms time since UNIX epoch in milliseconds""" ...
40,708
def compute_committee(indices: Sequence[ValidatorIndex], seed: Bytes32, index: uint64, count: uint64) -> Sequence[ValidatorIndex]: """ Return the committee corresponding to ``indices``, ``seed``, ``index``, and committee ``count``. """ st...
40,709
def get_default_graph(): """ Setting graphviz graph global options """ graph = Digraph('AWS', engine='dot') graph.body.append('splines=line') graph.body.append('rankdir=LR') graph.body.append('outputorder=edgesfirst') graph.node_attr.update(shape='rectangle', style='filled', color='black') r...
40,710
def GetJson(data): """ 将对象转换为JSON @data 被转换的对象(dict/list/str/int...) """ from json import dumps if data == bytes: data = data.decode('utf-8') return dumps(data)
40,711
def ribofy_phasing (): """ """ parser = argparse.ArgumentParser(description='get phasing') parser.add_argument("--bam", dest='bam', required=True, nargs="+", help="Bam file - sorted and indexed") parser.add_argument("--orfs", dest='orfs', required=True, help="orfs - generated by get_ORFs.py")...
40,712
def binary_tail(n: int) -> int: """ The last 1 digit and the following 0s of a binary representation, as a number """ return ((n ^ (n - 1)) + 1) >> 1
40,713
def time_left(expire_date): """Return remaining days before feature expiration or 0 if expired.""" today_dt = datetime.today() expire_dt = datetime.strptime(expire_date, "%d-%b-%Y") # Calculate remaining days before expiration days_left_td = expire_dt - today_dt days_left = days_left_td.day...
40,714
def run_intersect_default(cli_args): """ Run intersection benchmark using default search. """ print("Benchmark: intersect, assume_sorted=False") plot_intersect_benchmark(assume_sorted=False, n_average=cli_args.n) print("Benchmark: intersect, assume_sorted=True") plot_intersect_benchmark(ass...
40,715
def set_random_state(seed=1234567) : """seed : {None, int, array_like} Can be any integer between 0 and 2**32 - 1""" #return np.random.RandomState(seed) np.random.seed(seed)
40,716
def load_config(): """ importer_config.yaml must be in the current working directory """ with open(_PATH) as fd: config = yaml.safe_load(fd) # Remove trailing slashes from URLs config['kbase_endpoint'] = config['kbase_endpoint'].strip('/') return config
40,717
def start(connected, n_ai_players): """Starts the game with the given number of ai players and a list of connected players""" if n_ai_players < 0 or n_ai_players != int(n_ai_players): raise ValueError("n_ai_players must be a positive integer!") if len(cards) // (n_ai_players + len(connected)) < ...
40,718
def get_package_version(): """Return the Review Board version as a Python package version string. Returns: unicode: The Review Board package version. """ version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2] or VERSION[3]: version = '%s.%s' % (version, VERSION[2]) ...
40,719
def create_state_representation( name: str, state_space: StateSpace ) -> StateRepresentation: """Factory function for state representations Returns: Representation: """ # TODO: test if name == 'default': return DefaultStateRepresentation(state_space) if name == 'no_overlap...
40,720
def compressed_image( in_file: Union[str, Path], out_file: Union[str, Path] = None, ratio: float = 0.9 ): """ 说明: 压缩图片 参数: :param in_file: 被压缩的文件路径 :param out_file: 压缩后输出的文件路径 :param ratio: 压缩率,宽高 * 压缩率 """ in_file = IMAGE_PATH / in_file if isinstance(in_file, str...
40,721
def fit(x, y, sigy=None, error=False): """ Perform a linear fit on a range of x and y values. This function fits a set of data points x, y with individual standard deviations sigy for the y values to a straight line y = a + bx by minimizing chi-square. If the 'error' parameter is False the functio...
40,722
def eval_metrics_offline(cfg, pred_folder, palette, metrics=['mFscoreCD', 'mFscore'] ): """Calculate evaluation metrics from offline GT and prediction images, maily use the evaluate of dataset class Args: ...
40,723
def zero_pad_and_crop(img, amount=4): """Zero pad by `amount` zero pixels on each side then take a random crop. Args: img: numpy image that will be zero padded and cropped. amount: amount of zeros to pad `img` with horizontally and verically. Returns: The cropped zero padded img. The returned numpy ...
40,724
def video_id(video_id_or_url): """ Returns video id from given video id or url Parameters: ----------- video_id_or_url: str - either a video id or url Returns: -------- the video id """ if 'watch?v=' in video_id_or_url: return video_id_or_url.split('watch?v=')[1] e...
40,725
def check_permission(resource: Resource, permission_name: str) -> dict: """ Check if requester has sufficient permissions to do something on specific resource. Raises if not. """ base_permission_policy = resource.get_guest_authorization() if (authorization_header := resource.request.headers.get...
40,726
def finish(id): """Mark a SurveyResponse as finished Args: id (int): primary key of the surveyresponse to be returned """ resp = SurveyResponse.get(SurveyResponse.id == id) error_msg = "Response ID {0} is missing field {1}; can't mark as finished" # If we are missing any mandatory fie...
40,727
def makePalRecordsConsistent(pal_records, low_frequency, high_frequency, user_id, fcc_channel_id="1", start_date=None, end_date=None): """Make Pal object consistent with the inputs Args: pal_records: (list) A list of PAL Records in the form of dicti...
40,728
def read_config(): """Read from rotest.yml config elrados segment.""" config_path = search_config_file() if config_path is not None: with open(config_path, "r") as config_file: configuration_content = config_file.read() yaml_configuration = yaml.load(configuration_content) ...
40,729
def cast_to_str(some_value: typing.Any, from_type: typing.Any) -> typing.Any: """Just helper for creating suitable test assets.""" if from_type == bytes: return some_value.decode() return str(some_value)
40,730
def main(ini): """ Pull in configurations, main control function """ global the_silence global cache_overwrite global to_verify global tolerance global interval global show_load config = configparser.ConfigParser() try: config.read(ini_file) sections=config....
40,731
def downsample_by_group(df,min_distance=1.,message_callback=print): """Group and down-sample a DataFrame of xrsd records. Parameters ---------- df : pandas.DataFrame dataframe containing xrsd samples min_distance : float the minimum allowed nearest-neighbor distance ...
40,732
def plot_flux_profiles(data, filename='out.html', min_max=None, colors=None, **kwargs): """ :param data: pd.DataFrame :param filename: string :param min_max: tfa min/max output :return: """ # output to static HTML file ...
40,733
def get_pure_ratings( ratings: Union[str, pd.Series, pd.DataFrame] ) -> Union[str, pd.Series, pd.DataFrame]: """Removes rating watches/outlooks. Parameters ---------- ratings : str, pd.Series, or pd.DataFrame Rating may contain watch, such as `AA- *+`, `BBB+ (CwNegative)`. Outlook/w...
40,734
def clean_alignment(path, cache): """ Deletes the files generated by Mafft when called using build_alignment Args: path (str): The file path to the alignment file cache (Boolean): If true, the alignment file is kept. If false, the alignment file is also deleted """ filename =...
40,735
def export_grid(outname,resh,ignore=[255,0]): """[Exports given grid to a point cloud] Args: outname ([str]): [Output file name] resh ([np.array]): [3D Volume in grid representation] ignore (list, optional): [values to ignore]. Defaults to [255,0]. Returns: Grid as a point c...
40,736
def test_angle_format_conversions(maxn=5): """Tests min_to_vqsd and vqsd_to_min functions in runVQSD.""" for n in range(2, maxn + 1): params = np.array((n // 2) * [[[.1, .2, .3], [1, .2, .3], [.3, .2, 1], [.4, .2, .1]]] ) ...
40,737
def trainGenerator( batch_size, train_path, image_folder, mask_folder, aug_dict, image_color_mode="grayscale", mask_color_mode="grayscale", image_save_prefix="image", mask_save_prefix="mask", flag_multi_class=False, num_class=2, save_to_dir=None, target_size=(512, 512...
40,738
def sum_errors(dic): """Helper function to sum up number of failed jobs per host. Assumes that dic is in the form :param dict dic: {"error_code1":count1, "error_code2":count2, etc.} :return int: Sum of all values in dic """ return sum(value for key, value in dic.iteritems())
40,739
def checkFriends(new_user, usernameOfFriend): """ Check if users are friends or not""" # Check if users are friends first viewF = viewFriends(new_user, usernameOfFriend) # Check if users have any pending requests viewP = searchPendingRequests(new_user, usernameOfFriend) # Logic if viewF: ...
40,740
def update(instance, **data): """Update instance with data directly by using ``update()`` skipping calling ``save()`` method. Usage: ``instance = update(instance, some_field=some_value)`` """ instance.__class__.objects.filter(pk=instance.pk).update(**data) return refresh(instance)
40,741
def cast_distance_matrix_to_optimal_integer_type(D_X): """ Cast distance matrix to smallest signed integer type, sufficient to hold all its distances. Parameters ----------- D_X: np.array (|X|×|X|) Distance matrix of a compact metric space X with integer distances. Returns ...
40,742
def getObject(name): """Get reference to single Rhino object, checking for failure""" rc, obRef = Rhino.Input.RhinoGet.GetOneObject("Select " + name, True, Rhino.DocObjects.ObjectType.AnyObject) if rc != Rhino.Commands.Result.Success or not obRef : raise NameError(rc) return obRef
40,743
def get_falsecolor(input): """ picks false color bands from the 12 Sentinel bands (for visual interpretation of vegetation) :param input: 12-band image tensor :return: 3-band NIR-RED-GREEN tensor """ rgb_band_idxs = [bands.index(b) for b in ["S2B8", "S2B4", "S2B3"]] return input[rgb_band_idx...
40,744
def display_local_output(filename, output): """ Tell user where the local output will be """ message = "" \ "----------------------------------------------------\n" \ "* OUTPUT \n" bigquery_message = "" \ "*...
40,745
def migrate_files(homepath): """ Prepare ini file and SQL DB for new homepath. :param homepath: Path to data directory. :type homepath: str """ files = ("bbarchivist.ini", "bbarchivist.db") for file in files: oldfile = os.path.join(os.path.expanduser("~"), file) newfile = os...
40,746
def CUnescape(text): """Unescape a text string with C-style escape sequences to UTF-8 bytes.""" def ReplaceHex(m): # Only replace the match if the number of leading back slashes is odd. i.e. # the slash itself is not escaped. if len(m.group(1)) & 1: return m.group(1) + 'x0' + m.group(2) retur...
40,747
def apply_bin_op(left, right, op): """ Finds binary expression class suitable for combination of left and right expressions depending on whether their output is scalar or vector and creates instance of this expression with specified operation. """ exr_class = BIN_EXPR_CLASSES.get( (left....
40,748
def grafico_corrente(R, C, L, Vf, Vi, tempo, tipo, Sobre=[0, 0], Ii=0): """ Plota um grafico interatico depois de passado os valores das variaveis. :param R: Valor do Resistor. :param C: Valor do Capacitor. :param L: Valor do Indutor. :param Vf: Valor da Tensão na fonte, durante o...
40,749
def create_module(dotted_name=None, filename=None, *, update_parent=True): """Create a new blank module at run time, insert it into `sys.modules`, and return it. This is a utility function that closely emulates what Python's standard importer does. It fills in some attributes of the module, and inserts the...
40,750
def async_listen_platform( hass: core.HomeAssistant, component: str, callback: Callable[[str, dict[str, Any] | None], Any], ) -> None: """Register a platform loader listener. This method must be run in the event loop. """ service = EVENT_LOAD_PLATFORM.format(component) job = core.HassJo...
40,751
def pre_filter(image): """Apply morphological filter""" return cv2.morphologyEx(image, cv2.MORPH_OPEN, np.ones((3, 3)))
40,752
def build_corpus(docs: DocumentSet, *, remove_words=None, min_word_length=3, min_docs=5, max_docs_ratio=0.75, max_tokens=5000, replace_words=None, custom_bigrams=None, ngram_threshold=None ) -> Corpus: """ Build a `Corpus` object. This function takes the words...
40,753
def _Data_to_bytes(data: Data) -> bytes: """ Cast websockets.typing.Data to bytes. Parameters ---------- data : str | bytes Returns ------- bytes Either casted string or original bytes. """ return data.encode() if isinstance(data, str) else data
40,754
def run_pairs(genotype_df, variant_df, phenotype1_df, phenotype2_df, phenotype_pos_df, covariates1_df=None, covariates2_df=None, p1=1e-4, p2=1e-4, p12=1e-5, mode='beta', maf_threshold=0, window=1000000, batch_size=10000, logger=None, verbose=True): """Compute COLOC for all phenotype pair...
40,755
def main(local_argv): """ local_argv is the argument list, progrom name is first arugment this function prints the fibonacci list calcuated by the command line argument n """ if len(local_argv) != 2: print("must add one and only one command argument, , exit ") return ...
40,756
def alternate(*iterables): """ [a[0], b[0], ... , a[1], b[1], ..., a[n], b[n] ...] >>> alternate([1,4], [2,5], [3,6]) [1, 2, 3, 4, 5, 6] """ items = [] for tup in zip(*iterables): items.extend([item for item in tup]) return items
40,757
def softmax(x, axis=-1, t=-100.): """ Softmax operation Args: x (numpy.array): input X axis (int): axis for sum Return: **softmax** (numpy.array) - softmax(X) """ x = x - np.max(x) if np.min(x) < t: x = x/np.min(x)*t e_x = np.exp(x) return e_x / e_x.sum(axis, keepdims=True)
40,758
def format_params_in_str_format(format_string): """ Get the "parameter" indices/names of the format_string Args: format_string: A format string (i.e. a string with {...} to mark parameter placement and formatting Returns: A list of parameter indices used in the format string, in the or...
40,759
def AMO(df, M1=5, M2=10): """ 成交金额 :param M1: :param M2: :return: """ AMOUNT = df['amount'] AMOW = AMOUNT / 10000.0 AMO1 = MA(AMOW, M1) AMO2 = MA(AMOW, M2) return pd.DataFrame({ 'AMOW': AMOW, 'AMO1': AMO1, 'AMO2': AMO2 })
40,760
def test_try_minus(): """ @bors try- """ author = "jack" body = "@bors try-" commands = parse_issue_comment(author, body, commit, "bors") assert len(commands) == 1 command = commands[0] assert command.action == 'untry'
40,761
def tex_initial_states(data): """Initial states are texed.""" initial_state = [] initial_state = [''.join(["\lstick{\ket{", str(data['init'][row]),"}}"]) for row in range(len(data['init']))] return data, initial_state
40,762
def get_upgraded_dependencies_count(repo_path, django_dependency_sheet) -> tuple: """ Entry point to read, parse and calculate django dependencies @param repo_path: path for repo which we are calculating django deps @param django_dependency_sheet: csv which contains latest status of django deps @ret...
40,763
def first_order_gauge_action_matrix_for_prep(prep_superket_vec, target_sslbls, model_state_space, elemgen_gauge_basis, elemgen_row_basis): """ Returns a matrix for computing the *offset* of a given gate's error generator due to a local gauge action. Note: cliffor...
40,764
def FanOut(num): """Layer construction function for a fan-out layer.""" init_fun = lambda rng, input_shape: ([input_shape] * num, ()) apply_fun = lambda params, inputs, **kwargs: [inputs] * num return init_fun, apply_fun
40,765
def is_online(url="http://detectportal.firefox.com", expected=b"success\n"): """ Checks if the user is able to reach a selected hostname. :param hostname: The hostname to test against. Default is packages.linuxmint.com. :returns: True if able to connect or False otherwise. """ try: ...
40,766
def get_Data_temblor(): """Shows basic usage of the Sheets API. Creates a Sheets API service object and prints the names and majors of students in a sample spreadsheet: https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit """ credentials = get_credentials() ...
40,767
def triplet_loss(y_true, y_pred, alpha = 0.2): """ Implementation of the triplet loss as defined by formula (3) Arguments: y_true -- true labels, required when you define a loss in Keras, you don't need it in this function. y_pred -- python list containing three objects: anch...
40,768
def node_from_dict(node_dict): """Create a new node from its ``node_dict``. This is effectively a shorthand for choosing the correct node class and then calling its ``from_dict`` method. Args: node_dict (dict): dict-representation of the node. Returns: New schema node with the spe...
40,769
def test_noise_estimates_removal(): """Check noise estimation and noise removal using xarray and brute force using numpy. """ # Noise estimation via EchoData method ========= # Unpack data and convert to .nc file tmp = ConvertEK60(ek60_raw_path) tmp.raw2nc() # Read .nc file into an EchoDat...
40,770
def _get_activation(upsample_activation): """get activation""" nonlinear = getattr(nn, upsample_activation) return nonlinear
40,771
def computeSensitivity(P, W): """ The function at hand computes the sensitivity of each point using a reduction from L_\infty to L1. :return: None """ P = np.hstack((P, np.arange(P.shape[0])[:, np.newaxis])) B, idxs = applyBiCriterea(P[:, :-1], W) # attain set of flats which gives 2^j a...
40,772
def test_parse_time_expression(): """Test parse_time_expression.""" assert [x for x in range(60)] == dt_util.parse_time_expression("*", 0, 59) assert [x for x in range(60)] == dt_util.parse_time_expression(None, 0, 59) assert [x for x in range(0, 60, 5)] == dt_util.parse_time_expression("/5", 0, 59) ...
40,773
def test_starting_a_job_template(mock): """Test launching a job template""" job_id = "Hundley" service_offering = ServiceOfferingFactory( kind=OfferingKind.JOB_TEMPLATE, source_ref=98 ) mock.return_value = Mock(id=job_id) params = {"service_parameters": "xyz"} obj = StartTowerJob(se...
40,774
def num_bytes_needed_for_data(rom_dict): """ Get the number of bytes to store the largest data in the rom. Args: rom_dict (dict(int:int)): Dictionary of address and data values Returns: (int): Number of bytes needed for largest piece of data """ largest_data = max(rom_dict.iterv...
40,775
def run_simulation(model, **kwargs): """Runs the given model using KaSim and returns the parsed results. Parameters ---------- **kwargs : List of keyword arguments All keyword arguments specifying conditions for the simulation are passed to the function :py:func:`run_kasim` (see documen...
40,776
def _bot_exists(botname): """ Utility method to import a bot. """ module = None try: module = importlib.import_module('%s.%s' % (botname, botname)) except ImportError as e: quit('Unable to import bot "%s.%s": %s' % (botname, botname, str(e))) return module
40,777
def cli(): """ Calculate mortgage payments """ pass
40,778
def printif(*thing, b=False): """ Print ``thing`` if ``b`` is true :param thing: The thing. :param b: The condition. :return: None """ if (b): print(*thing)
40,779
def validator(fn): """Decorator that constructs a scenario validator from given function. Decorated function should return ValidationResult on error. :param fn: function that performs validation :returns: rally scenario validator """ def wrap_given(*args, **kwargs): """Dynamic validati...
40,780
def bootstrap_alert_message(msg, alert_type): """ Wrap Ajax error message for display :param msg: Message text :param alert_type: must be alert-danger, alert-success, alert-info, alert-warning :return: html formatted message """ if not msg: msg = _('An unknown error has occurred') ...
40,781
def get_message_dispatched(correlation_id, steps, primary=True): """ Sets a flag in cache to indicate that a message has been dispatched. :param correlation_id: a str guid for the fsm :param steps: an integer corresponding to the step in the fsm execution :return: True if cached and False otherwise...
40,782
def _format_exponent_notation(input_number, precision, num_exponent_digits): """ Format the exponent notation. Python's exponent notation doesn't allow for a user-defined number of exponent digits. Based on [Anurag Uniyal's answer][answer] to the StackOverflow question ['Python - number of digits i...
40,783
def unicode_blackboard_activity_stream( activity_stream: typing.List[blackboard.ActivityItem]=None, indent: int=0, show_title: bool=True ): """ Pretty print the blackboard stream to console. Args: activity_stream: the log of activity, if None, get the entire activity stream inde...
40,784
def parse_args(args): """Parse command line parameters Args: args ([str]): command line parameters as list of strings Returns: :obj:`argparse.Namespace`: command line parameters namespace """ parser = argparse.ArgumentParser( description="Snapcraft Jsonnet parser") parser.a...
40,785
def normalize(vector): """Normalize a vector to unit length. Args: vector (list/tuple/numpy.ndarray): Array to be normalized Return: vector (numpy.ndarray): Normalized vector. """ length = np.sqrt(np.sum(np.asarray(vector) ** 2)) if length == 0: return np.asarray(vector...
40,786
def get_struc_qty(*args): """get_struc_qty() -> size_t""" return _idaapi.get_struc_qty(*args)
40,787
def evaluate0(gametree_: Callable[[Board], Node], static_eval_: Callable[[Board], int], prune_: Callable[[Node], Node]) -> Callable[[Board], int]: """Return a tree evaluation function""" def evaluate_(board: Board) -> int: return maximize0(maptree(static_...
40,788
def fortune(inp): """ .fortune -- returns one random card and it's fortune """ try: cards = http.get_json("https://tarot-api.com/draw/1") except HTTPError: return "The spirits are displeased." card = cards[0] return card["name"] + ": " + ", ".join(card["keywords"])
40,789
def declin_0(x, obl): """ declination of a point of ecliptic :param x: longitude of the point in degree :param obl: obliquity of the ecliptic in degree return declination in degree """ return DEG * m.asin(m.sin(x * RAD) * m.sin(obl * RAD))
40,790
def network_data_structures(stream_names_tuple, agent_descriptor_dict): """Builds data structures for the network. These data structures are helpful for animating the network and for building networks of processes. Parameters ---------- Same as for make_network. Return Values ------...
40,791
def to_onnx(model, X=None, name=None, initial_types=None, target_opset=None, options=None, rewrite_ops=False, white_op=None, black_op=None, final_types=None): """ Converts a model using on :epkg:`sklearn-onnx`. @param model model to convert or a function ...
40,792
def setRx(phi): """Rotation matrix around x axis""" Rx = np.zeros((phi.size,3,3)) Rx[:,0,0] = 1. Rx[:,1,1] = np.cos(phi) Rx[:,2,2] = Rx[:,0,0] Rx[:,1,2] = -np.sin(phi) Rx[:,2,1] = -Rx[:,0,2] return Rx
40,793
def discrete_resample(df, freq_code, agg_fun, remove_inter=False, **kwargs): """ Function to properly set up a resampling class for discrete data. This assumes a linear interpolation between data points. Parameters ---------- df: DataFrame or Series DataFrame or Series with a time index. ...
40,794
def reflect(data, width): """Ceflect a data word, means revert the bit order.""" reflected = data & 0x01 for _ in range(width - 1): data >>= 1 reflected = (reflected << 1) | (data & 0x01) return reflected
40,795
def snell_angle_2(angle_1, n_1, n_2): """Calculate the angle of refraction of a ray travelling between two mediums according to Snell's law. Args: angle_1 (array_like[float]): angle of incidence with respect to surface normal in radians. n_1 (float): index of refraction in first medium....
40,796
def npv(ico, nci, r, n): """ This capital budgeting function computes the net present value on a cash flow generating investment. ico = Initial Capital Outlay nci = net cash inflows per period r = discounted rate n = number of periods Example: npv(100000, 15000, .03, 10) """ pv_nc...
40,797
def instrument_endpoint(time_fn=time.time): """Decorator to instrument Cloud Endpoint methods.""" def decorator(fn): method_name = fn.__name__ assert method_name @functools.wraps(fn) def decorated(service, *args, **kwargs): service_name = service.__class__.__name__ endpoint_name = '/_ah/...
40,798
def test_in_match_disabled_password(current_actor_context): """ Configuration file in this format: # PermitRootLogin yes # implicit Match address 192.168.* PermitRootLogin prohibit-password """ config = OpenSshConfig( permit_root_login=[ OpenSshPermitRootLogi...
40,799