id
int64
11
59.9k
original
stringlengths
33
150k
modified
stringlengths
37
150k
45,714
def forecast( R, metadata, V, timesteps, n_ens_members=24, n_cascade_levels=6, win_size=256, overlap=0.1, war_thr=0.1, extrap_method="semilagrangian", decomp_method="fft", bandpass_filter_method="gaussian", noise_method="ssft", ar_order=2, vel_pert_method=None...
def forecast( R, metadata, V, timesteps, n_ens_members=24, n_cascade_levels=6, win_size=256, overlap=0.1, war_thr=0.1, extrap_method="semilagrangian", decomp_method="fft", bandpass_filter_method="gaussian", noise_method="ssft", ar_order=2, vel_pert_method=None...
31,588
def get_dns_history_command(client, args): hostname = args.get('hostname') record_type = args.get('type') page = int(args.get('page', 1)) res = client.get_dns_history(hostname=hostname, record_type=record_type, page=page) res = {k: v for k, v in res.items() if k not in removed_keys} records_list...
def get_dns_history_command(client, args): hostname = args.get('hostname') record_type = args.get('type') page = int(args.get('page', 1)) res = client.get_dns_history(hostname=hostname, record_type=record_type, page=page) res = {k: v for k, v in res.items() if k not in removed_keys} records_list...
25,614
def _mix_latent_gp(W, g_mu, g_var, full_cov, full_output_cov): r""" Takes the mean and variance of a uncorrelated L-dimensional latent GP and returns the mean and the variance of the mixed GP, `f = W \times g`, where both f and g are GPs. :param W: [P, L] :param g_mu: [..., N, L] :param g_v...
def _mix_latent_gp(W, g_mu, g_var, full_cov, full_output_cov): r""" Takes the mean and variance of a uncorrelated L-dimensional latent GP and returns the mean and the variance of the mixed GP, `f = W \times g`, where both f and g are GPs. :param W: [P, L] :param g_mu: [..., N, L] :param g_v...
28,068
def build_stat_coll_cmd(action, config, source): """ Build the statistics collector analysis command. """ cmd = [config.analyzer_binary, '-c', '-x', action.lang, '--analyze', # Do not warn about the unused gcc/g++ arguments. '-Qunused-arguments', '--analyzer-output', 't...
def build_stat_coll_cmd(action, config, source): """ Build the statistics collector analysis command. """ cmd = [config.analyzer_binary, '-c', '-x', action.lang, '--analyze', # Do not warn about the unused gcc/g++ arguments. '-Qunused-arguments', '--analyzer-output', 't...
41,176
def _gen_gray_code(n: int): """Generate the Gray Code from 0 to 2^n-1. Each iteration returns two elements. The first element is the decimal representation of the gray code and the second one is the position of bits flipped for next gray code. """ gray_code = 0 for i in range(1, 2 ** n): ...
def _gen_gray_code(n: int): """Generate the Gray Code from 0 to 2^n-1. Each iteration returns two elements. The first element is the decimal representation of the gray code and `bit_flip` is the position of bits flipped for next gray code. """ gray_code = 0 for i in range(1, 2 ** n): ne...
45,350
def _predict( booster, data, **kwargs, ): """ Run distributed prediction with a trained booster on Ray backend. During work it runs xgb.predict on each worker for row partition of `data` and creates Modin DataFrame with prediction results. Parameters ---------- booster : xgboos...
def _predict( booster, data, **kwargs, ): """ Run distributed prediction with a trained booster on Ray backend. During work it runs xgb.predict on each worker for row partition of `data` and creates Modin DataFrame with prediction results. Parameters ---------- booster : xgboos...
27,786
def _parse_ini_file(path: Path) -> PARSE_RESULT: """Parses .ini files with expected pytest.ini sections todo: investigate if tool:pytest should be added """ iniconfig = _parse_ini_config(path) if "pytest" in iniconfig: return dict(iniconfig["pytest"].items()) return None
def _parse_ini_file(path: Path) -> PARSE_RESULT: """Parses .ini files with expected pytest.ini sections TODO: Investigate if tool:pytest should be added. """ iniconfig = _parse_ini_config(path) if "pytest" in iniconfig: return dict(iniconfig["pytest"].items()) return None
13,416
def test_13_verify_logs_collection_still_work_after_moving_the_system_dataset_to_the_second_pool(logs_data): cmd = "cat /var/log/middlewared.log" middlewared_log = SSH_TEST(cmd, user, password, ip) assert middlewared_log['result'] is True, str(middlewared_log) logs_data['middleware_log_5'] = middlewared...
def test_13_verify_logs_after_sysds_is_moved_to_second_pool(logs_data): cmd = "cat /var/log/middlewared.log" middlewared_log = SSH_TEST(cmd, user, password, ip) assert middlewared_log['result'] is True, str(middlewared_log) logs_data['middleware_log_5'] = middlewared_log['output'].splitlines()[-1] a...
13,908
def parse_coverage( lines: List[str], *, filename: str, exclude_lines_by_pattern: Optional[str], exclude_branches_by_pattern: Optional[str], exclude_pattern_prefix: Optional[str], flags: ParserFlags, ) -> FileCoverage: """ Extract coverage data from a gcov report. Logging: P...
def parse_coverage( lines: List[str], *, filename: str, exclude_lines_by_pattern: Optional[str], exclude_branches_by_pattern: Optional[str], exclude_pattern_prefix: Optional[str], flags: ParserFlags, ) -> FileCoverage: """ Extract coverage data from a gcov report. Logging: P...
13,742
def _enqueue_recompute_grades_task(course_key, grading_policy_hash=None): kwargs = { 'course_key': six.text_type('course_key'), 'event_transaction_id': six.text_type(get_event_transaction_id()), 'event_transaction_type': six.text_type(get_event_transaction_type()), } if grading_polic...
def _enqueue_recompute_grades_task(course_key, grading_policy_hash=None): kwargs = { 'course_key': str('course_key'), 'event_transaction_id': six.text_type(get_event_transaction_id()), 'event_transaction_type': six.text_type(get_event_transaction_type()), } if grading_policy_hash is ...
54,082
def _get_maintenance_config(cmd, client, file_path): # get models MaintenanceConfiguration = cmd.get_models('MaintenanceConfiguration', resource_type=CUSTOM_MGMT_AKS_PREVIEW, operation_group='maintenance_configurations') TimeInWeek = cmd.get_models('TimeInWeek', resource_type=CUSTOM_MGMT_AKS_PREVIEW, operat...
def _get_maintenance_config(cmd, file_path): maintenance_config = get_file_json(file_path) return maintenance_config # get models MaintenanceConfiguration = cmd.get_models('MaintenanceConfiguration', resource_type=CUSTOM_MGMT_AKS_PREVIEW, operation_group='maintenance_configurations') TimeInWeek = cm...
43,928
def expansion(la, lb, ra, rb, alpha, beta, t): r"""Compute Hermite Gaussian expansion coefficients recursively for two Gaussian functions. An overlap distribution, which defines the product of two Gaussians, can be written as a Hermite expansion as [`Helgaker (1995) p798 <https://www.worldscientific.com/do...
def expansion(la, lb, ra, rb, alpha, beta, t): r"""Compute Hermite Gaussian expansion coefficients recursively for two Gaussian functions. An overlap distribution, which defines the product of two Gaussians, can be written as a Hermite expansion as [`Helgaker (1995) p798 <https://www.worldscientific.com/do...
24,594
def thermal_speed_coefficients(method: str, ndim: int) -> float: r""" Get the appropriate coefficient for calculating the thermal speed :math:`v_{th}` based on the given ``method`` and ``ndim``. (See the `~plasmapy.formulary.parameters.thermal_speed` :ref:`Notes <thermal-speed-notes>` section for f...
def thermal_speed_coefficients(method: str, ndim: int) -> float: r""" Get the appropriate coefficient for calculating the thermal speed :math:`v_{th}` based on the given ``method`` and ``ndim``. (See the `~plasmapy.formulary.parameters.thermal_speed` :ref:`Notes <thermal-speed-notes>` section for f...
41,696
def unpack_buffer( buffer: JsProxy, *, filename: str = "", format: str = None, target: Literal["site", "lib", None] = None, extract_dir: str = None, calculate_dynlibs: bool = False, ) -> Optional[JsProxy]: """Used to install a package either into sitepackages or into the standard lib...
def unpack_buffer( buffer: JsProxy, *, filename: str = "", format: str = None, target: Literal["site", "lib", None] = None, extract_dir: str = None, calculate_dynlibs: bool = False, ) -> Optional[JsProxy]: """Used to install a package either into sitepackages or into the standard lib...
2,155
def mean_variance_axis(X, axis, weights=None, return_sum_weights=False): """Compute mean and variance along an axix on a CSR or CSC matrix Parameters ---------- X : CSR or CSC sparse matrix, shape (n_samples, n_features) Input data. axis : int (either 0 or 1) Axis along which the a...
def mean_variance_axis(X, axis, weights=None, return_sum_weights=False): """Compute mean and variance along an axix on a CSR or CSC matrix Parameters ---------- X : CSR or CSC sparse matrix, shape (n_samples, n_features) Input data. axis : int (either 0 or 1) Axis along which the a...
22,443
def arg_parser(): parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument('-u', '--galaxy-url', default="http://localhost:8080", help='Galaxy URL') parser.add_argument('-k', '--key', default=None, help='Galaxy User API Key') parser.add_argument('-a', '--admin-key', default=None, he...
def arg_parser(): parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument('-u', '--galaxy-url', default="http://localhost:8080", help='Galaxy URL') parser.add_argument('-k', '--key', default=None, help='Galaxy User API Key') parser.add_argument('-a', '--admin-key', default=None, he...
42,678
def _populate_db_with_balances(connection, ts: Timestamp): cursor = connection.cursor() cursor.execute('INSERT OR IGNORE INTO assets(identifier) VALUES(?)', (NFT_TOKEN_ID,)) cursor.execute( """ INSERT INTO "timed_balances" ("category", "time", "currency", "amount", "usd_value") VALUES ...
def _populate_db_with_balances(connection, ts: Timestamp): cursor = connection.cursor() cursor.execute('INSERT OR IGNORE INTO assets(identifier) VALUES(?)', (NFT_TOKEN_ID,)) cursor.execute( """ INSERT INTO timed_balances ("category", "time", "currency", "amount", "usd_value") VALUES ...
31,753
def collect_entries_data_from_response(parsed_feed_data: FeedParserDict) -> List[Dict[str, Any]]: """Collects relevant data from the parsed RSS feed entries. Args: parsed_feed_data (FeedParserDict): Parsed RSS feed data. Returns: List[Dict[str, Any]]: The data from the RSS feed relevant fo...
def collect_entries_data_from_response(parsed_feed_data: FeedParserDict) -> List[Dict[str, Any]]: """Collects relevant data from the parsed RSS feed entries. Args: parsed_feed_data (FeedParserDict): Parsed RSS feed data. Returns: List[Dict[str, Any]]: The data from the RSS feed relevant fo...
32,051
def relationships_manager(client: Client, entity_a: str, entity_a_type: str, indicator_type: str, indicator: str, field_for_passive_dns_rs: str, feed_indicator_type_for_passive_dns_rs: str): """ manage the relationships creation Args: client: Client object with request ...
def relationships_manager(client: Client, entity_a: str, entity_a_type: str, indicator_type: str, indicator: str, field_for_passive_dns_rs: str, feed_indicator_type_for_passive_dns_rs: str): """ manage the relationships creation Args: client: Client object with request ...
23,006
def test_read_csv_skiprows_range(): with filetext(csv_text) as fn: f = dd.read_csv(fn, skiprows=range(5)) result = f.compute(scheduler='sync') expected = pd.read_csv(fn, skiprows=range(5)) assert_eq(result, expected)
def test_read_csv_skiprows_range(): with filetext(csv_text) as fn: f = dd.read_csv(fn, skiprows=range(5)) result = f expected = pd.read_csv(fn, skiprows=range(5)) assert_eq(result, expected)
34,875
def keras_op_to_relay(inexpr, keras_layer, outname, etab): """Convert keras layer to relay expr, and update etab. Parameters ---------- inexpr : relay.expr.Expr or a list of it The input relay expr(s) keras_layer : keras.layers The keras layer to be converted outname : str ...
def keras_op_to_relay(inexpr, keras_layer, outname, etab): """Convert keras layer to relay expr, and update etab. Parameters ---------- inexpr : relay.expr.Expr or a list of it The input Relay expression(s). keras_layer : keras.layers The keras layer to be converted outname : ...
38,971
def field_singleton_schema( # noqa: C901 (ignore complexity) field: ModelField, *, by_alias: bool, model_name_map: Dict[Type['BaseModel'], str], schema_overrides: bool = False, ref_prefix: Optional[str] = None, known_models: Set[Type['BaseModel']], ) -> Tuple[Dict[str, Any], Dict[str, Any],...
def field_singleton_schema( # noqa: C901 (ignore complexity) field: ModelField, *, by_alias: bool, model_name_map: Dict[Type['BaseModel'], str], schema_overrides: bool = False, ref_prefix: Optional[str] = None, known_models: Set[Type['BaseModel']], ) -> Tuple[Dict[str, Any], Dict[str, Any],...
3,543
def delete_versions_from_db(project, version_data): """ Delete all versions not in the current repo. :returns: The slug of the deleted versions from the database, and the slug of active versions that where deleted from the repository. """ # We use verbose_name for tags # because several tag...
def delete_versions_from_db(project, version_data): """ Delete all versions not in the current repo. :returns: The slug of the deleted versions from the database, and the slug of active versions that were deleted from the repository. """ # We use verbose_name for tags # because several tags...
57,817
def main(): try: args = demisto.args() last_seen_gte = args.get('from') last_seen_lte = args.get('to') limit = args.get('limit', '100') get_endpoints_args = {'limit': limit} if last_seen_gte: get_endpoints_args['last_seen_gte'] = last_seen_gte if ...
def main(): try: args = demisto.args() last_seen_gte = args.get('from') last_seen_lte = args.get('to') limit = args.get('limit', '100') get_endpoints_args = {'limit': limit} if last_seen_gte: get_endpoints_args['last_seen_gte'] = last_seen_gte if ...
12,767
def _preprocessed_interpreter_search_paths( env_tgt: EnvironmentTarget, _search_paths: Iterable[str], is_default: bool, ) -> tuple[str, ...]: """Checks for special search path strings, and errors if any are invalid for the environment. This will return: * The search paths, unaltered, for local/...
def _preprocessed_interpreter_search_paths( env_tgt: EnvironmentTarget, _search_paths: Iterable[str], is_default: bool, ) -> tuple[str, ...]: """Checks for special search path strings, and errors if any are invalid for the environment. This will return: * The search paths, unaltered, for local/...
5,252
def _load_word2vec_format(cls, fname, fvocab=None, binary=False, encoding='utf8', unicode_errors='strict', limit=None, datatype=REAL, binary_chunk_size=100 * 1024): """Load the input-hidden weight matrix from the original C word2vec-tool format. Note that the information stored in the...
def _load_word2vec_format(cls, fname, fvocab=None, binary=False, encoding='utf8', unicode_errors='strict', limit=None, datatype=REAL, binary_chunk_size=100 * 1024): """Load the input-hidden weight matrix from the original C word2vec-tool format. Note that the information stored in the...
26,112
def test_view_change_not_happen_if_ic_is_discarded(looper, txnPoolNodeSet, sdk_pool_handle, sdk_wallet_client, tconf, tdir, allPluginsPath): """ 1. panic_node ...
def test_view_change_not_happen_if_ic_is_discarded(looper, txnPoolNodeSet, sdk_pool_handle, sdk_wallet_client, tconf, tdir, allPluginsPath): """ 1. panic_node ...
4,224
def annotate_muscle(raw, threshold=1.5, picks=None, min_length_good=.1): """Detect segments with muscle artifacts. Detects segments periods that contains high frequency activity beyond the specified threshold. Muscle artifacts are most notable in the range of 110- 140Hz. Raw data is band pass filt...
def annotate_muscle(raw, threshold=1.5, picks=None, min_length_good=.1): """Detect segments with muscle artifacts. Detects segments periods that contains high frequency activity beyond the specified threshold. Muscle artifacts are most notable in the range of 110- 140Hz. Raw data is band pass filt...
23,114
def check_index(axis, ind, dimension): """Check validity of index for a given dimension Examples -------- >>> check_index(0, 3, 5) >>> check_index(0, 5, 5) Traceback (most recent call last): ... IndexError: Index 5 is out of bounds for axis 0 with size 5 >>> check_index(1, 6, 5) ...
def check_index(axis, ind, dimension): """Check validity of index for a given dimension Examples -------- >>> check_index(0, 3, 5) >>> check_index(0, 5, 5) Traceback (most recent call last): ... IndexError: Index 5 is out of bounds for axis 0 with size 5 >>> check_index(1, 6, 5) ...
5,444
def install(name=None, refresh=False, pkgs=None, version=None, test=False, **kwargs): """ Install the named fileset(s)/rpm package(s). .. versionadded:: 3005 preference to install rpm packages are to use in the following order: /opt/freeware/bin/dnf /opt/freeware/bin/yum ...
def install(name=None, refresh=False, pkgs=None, version=None, test=False, **kwargs): """ Install the named fileset(s)/rpm package(s). .. versionadded:: 3005 preference to install rpm packages are to use in the following order: /opt/freeware/bin/dnf /opt/freeware/bin/yum ...
24,881
def _loop_exits_early(loop): """ Returns true if a loop mays end up in a break statement. Args: loop (astroid.For, astroid.While): the loop node inspected. Returns: bool: True if the loop mays end up in a break statement, False otherwise. """ loop_nodes = (nodes.For, nodes.Whil...
def _loop_exits_early(loop): """ Returns true if a loop mays end up in a break statement. Args: loop (astroid.For, astroid.While): the loop node inspected. Returns: bool: True if the loop may end with a break statement, False otherwise. """ loop_nodes = (nodes.For, nodes.While)...
13,564
def QR_iteration(H, shifts): """Perform the QR iteration. Performs a QR step for each shift provided in `shifts`. `H` is assumed to be an unreduced upper Hessenberg matrix. If a complex shift occurs a double step is peformed in order to avoid complex arithmetic. Parameters ---------- H ...
def QR_iteration(H, shifts): """Perform the QR iteration. Performs a QR step for each shift provided in `shifts`. `H` is assumed to be an unreduced upper Hessenberg matrix. If a complex shift occurs a double step is peformed in order to avoid complex arithmetic. Parameters ---------- H ...
28,583
def plot_ppc( data, kind="kde", alpha=None, mean=True, observed=True, color=None, colors=None, grid=None, figsize=None, textsize=None, data_pairs=None, var_names=None, filter_vars=None, coords=None, flatten=None, flatten_pp=None, num_pp_samples=None, ...
def plot_ppc( data, kind="kde", alpha=None, mean=True, observed=True, color=None, colors=None, grid=None, figsize=None, textsize=None, data_pairs=None, var_names=None, filter_vars=None, coords=None, flatten=None, flatten_pp=None, num_pp_samples=None, ...
38,271
def build_node_set(node, s=None): """Build a set of all the nodes in a rapidz graph Parameters ---------- node : Stream The node to use as a starting point for building the set s : set or None The set to put the nodes into. If None return a new set full of nodes Returns ---...
def build_node_set(node, s=None): """Build a set of all the nodes in a streamz graph Parameters ---------- node : Stream The node to use as a starting point for building the set s : set or None The set to put the nodes into. If None return a new set full of nodes Returns --...
3,425
def _symbolicate(profile: MutableMapping[str, Any], project: Project) -> MutableMapping[str, Any]: symbolicator = Symbolicator(project=project, event_id=profile["profile_id"]) modules = profile["debug_meta"]["images"] stacktraces = [ { "registers": {}, "frames": s["frames"], ...
def _symbolicate(profile: MutableMapping[str, Any], project: Project) -> MutableMapping[str, Any]: symbolicator = Symbolicator(project=project, event_id=profile["profile_id"]) modules = profile["debug_meta"]["images"] stacktraces = [ { "registers": {}, "frames": s["frames"], ...
31,062
def main(): try: if demisto.command() == 'test-module': # Tests connectivity and credentails on login # generateStartEndDates(1) return "ok" elif demisto.command() == 'ironportQuarantineReleaseEmail': mesId = demisto.args().get('mid') ir...
def main(): try: if demisto.command() == 'test-module': # Tests connectivity and credentails on login # generateStartEndDates(1) return "ok" elif demisto.command() == 'iron-port-quarantine-release-email': mesId = demisto.args().get('mid') ...
42,781
def test_dataframe_multiIndex_index(): """Test for multiIndex dataframe""" data = { "x": pd.DataFrame([[2, 3], [6, 7]], index=pd.MultiIndex.from_arrays([['a', 'b'], ['y', 'z']])) } with pytest.raises(ValueError): assert expand_grid(others=data)
def test_dataframe_multi_index_index(): """Test for multiIndex dataframe""" data = { "x": pd.DataFrame([[2, 3], [6, 7]], index=pd.MultiIndex.from_arrays([['a', 'b'], ['y', 'z']])) } with pytest.raises(ValueError): assert expand_grid(others=data)
47,982
def init_telemetry(): try: import openvino_telemetry as tm # pylint:disable=C0415 except ImportError: return None try: telemetry = tm.Telemetry('Accuracy Checker', version=__version__, tid='UA-194864834-1') return telemetry except Exception: # pylint:disable=W0703 ...
def init_telemetry(): try: import openvino_telemetry as tm # pylint:disable=C0415 except ImportError: return None try: telemetry = tm.Telemetry('Accuracy Checker', app_version= __version__, tid='UA-194864834-1') return telemetry except Exception: # pylint:disable=W0703 ...
31,766
def main(): params = demisto.params() args = demisto.args() url = params.get('url') verify_certificate = not params.get('insecure', False) proxy = params.get('proxy', False) headers = {} headers['PRIVATE-TOKEN'] = f'{params["api_key"]}' command = demisto.command() LOG(f'Command bein...
def main(): params = demisto.params() args = demisto.args() url = params.get('url') verify_certificate = not params.get('insecure', False) proxy = params.get('proxy', False) headers = {} headers['PRIVATE-TOKEN'] = f'{params["api_key"]}' command = demisto.command() LOG(f'Command bein...
27,941
def main(): parser = argparse.ArgumentParser('Train a neural network on MNIST dataset') parser.add_argument( '--batchsize', '-B', type=int, default=100, help='Batch size') parser.add_argument( '--epoch', '-E', type=int, default=20, help='Number of epochs to train') parser.add_arg...
def main(): parser = argparse.ArgumentParser('Train a neural network on MNIST dataset') parser.add_argument( '--batchsize', '-B', type=int, default=100, help='Batch size') parser.add_argument( '--epoch', '-E', type=int, default=20, help='Number of epochs to train') parser.add_arg...
52,237
def app_ssowatconf(): """ Regenerate SSOwat configuration file """ from yunohost.domain import domain_list, _get_maindomain, domain_config_get from yunohost.permission import user_permission_list main_domain = _get_maindomain() domains = domain_list()["domains"] all_permissions = user...
def app_ssowatconf(): """ Regenerate SSOwat configuration file """ from yunohost.domain import domain_list, _get_maindomain, domain_config_get from yunohost.permission import user_permission_list main_domain = _get_maindomain() domains = domain_list()["domains"] all_permissions = user...
566
def _get_feature_flag_items(domain, couch_user): user_is_admin = couch_user.is_domain_admin(domain) from corehq.apps.domain.views.fixtures import LocationFixtureConfigView feature_flag_items = [] if user_is_admin and toggles.SYNC_SEARCH_CASE_CLAIM.enabled(domain): feature_flag_items.append({ ...
def _get_feature_flag_items(domain, couch_user): user_is_admin = couch_user.is_domain_admin(domain) from corehq.apps.domain.views.fixtures import LocationFixtureConfigView feature_flag_items = [] if user_is_admin and toggles.SYNC_SEARCH_CASE_CLAIM.enabled(domain): feature_flag_items.append({ ...
25,578
def queue_channel_open( nodeaddress_to_channelopenqueue: OpenQueue, nodeaddress_to_channeldepositqueue: DepositQueue, channel: Dict, token_address: str, node_to_address: Dict, node_to_endpoint: Dict, ) -> None: node1 = channel["node1"] node2 = channel["node2"] participant1 = node_to...
def queue_channel_open( nodeaddress_to_channelopenqueue: OpenQueue, nodeaddress_to_channeldepositqueue: DepositQueue, channel: Dict, token_address: str, node_to_address: Dict, node_to_endpoint: Dict, ) -> None: node1 = channel["node1"] node2 = channel["node2"] participant1 = node_to...