id
int64
11
59.9k
original
stringlengths
33
150k
modified
stringlengths
37
150k
46,600
def deprecated( key: str, message: str = "'$KEY' is deprecated. Change your code and config to use '$NEW_KEY'", *, _parent_: Container, _node_: Optional[Node], ) -> Any: from omegaconf._impl import select_node if not isinstance(key, str): raise ValueError( f"oc.deprecate...
def deprecated( key: str, message: str = "'$KEY' is deprecated. Change your code and config to use '$NEW_KEY'", *, _parent_: Container, _node_: Optional[Node], ) -> Any: from omegaconf._impl import select_node if not isinstance(key, str): raise TypeError( f"oc.deprecated...
35,159
def gmres(A, b, x0=None, tol=1e-5, restart=None, maxiter=None, M=None, callback=None, atol=None, callback_type=None): """Uses Generalized Minimal RESidual iteration to solve ``Ax = b``. Args: A (cupy.ndarray or cupyx.scipy.sparse.spmatrix): The real or complex matrix of the linear...
def gmres(A, b, x0=None, tol=1e-5, restart=None, maxiter=None, M=None, callback=None, atol=None, callback_type=None): """Uses Generalized Minimal RESidual iteration to solve ``Ax = b``. Args: A (cupy.ndarray or cupyx.scipy.sparse.spmatrix): The real or complex matrix of the linear...
46,378
def unit_get_expanded_info(country_name: str, unit_type, request_type: str) -> str: original_name = unit_type.name and unit_type.name or unit_type.id id = unit_type.id default_value = None faction_value = None with UNITINFOTEXT_PATH.open("r", encoding="utf-8") as fdata: data = json.load(fdat...
def unit_get_expanded_info(country_name: str, unit_type, request_type: str) -> str: original_name = unit_type.name and unit_type.name or unit_type.id id = unit_type.id default_value = None faction_value = None with UNITINFOTEXT_PATH.open("r", encoding="utf-8") as fdata: data = json.load(fdat...
7,241
def test_uint_image(): img = np.random.randint(0, 255, (10, 10), dtype=np.uint8) labels = np.zeros((10, 10), dtype=np.int64) labels[1:3, 1:3]=1 labels[6:9, 6:9] = 2 output = label2rgb(labels, image=img, bg_label=0) # Make sure that the output is made of floats and in the correct range assert...
def test_uint_image(): img = np.random.randint(0, 255, (10, 10), dtype=np.uint8) labels = np.zeros((10, 10), dtype=np.int64) labels[1:3, 1:3] = 1 labels[6:9, 6:9] = 2 output = label2rgb(labels, image=img, bg_label=0) # Make sure that the output is made of floats and in the correct range asse...
7,575
def test_votable_tag(): xml = votable_xml_string('1.1') assert 'xmlns="http://www.ivoa.net/xml/VOTable/v1.1"' in xml assert 'xsi:noNamespaceSchemaLocation="http://www.ivoa.net/xml/VOTable/v1.1"' in xml xml = votable_xml_string('1.2') assert 'xmlns="http://www.ivoa.net/xml/VOTable/v1.2"' in xml ...
def test_votable_tag(): xml = votable_xml_string('1.1') assert 'xmlns="http://www.ivoa.net/xml/VOTable/v1.1"' in xml assert 'xsi:noNamespaceSchemaLocation="http://www.ivoa.net/xml/VOTable/v1.1"' in xml xml = votable_xml_string('1.2') assert 'xmlns="http://www.ivoa.net/xml/VOTable/v1.2"' in xml ...
30,710
def download_zip_file_from_gc(current_feature_content_zip_file_path, extract_destination_path): """Save the content_new.zip file from the feature branch into artifacts folder. Args: gc_service_account: full path to service account json. current_feature_content_zip_file_path (str): Content_new.z...
def download_zip_file_from_gcp(current_feature_content_zip_file_path, extract_destination_path): """Save the content_new.zip file from the feature branch into artifacts folder. Args: gc_service_account: full path to service account json. current_feature_content_zip_file_path (str): Content_new....
41,538
def segment_volume(folder_model, fname_image, fname_roi=None): """Segment an image. Segment an image (fname_image) using a already trained model given its training parameters (both in folder_model). If provided, a RegionOfInterest (fname_roi) is used to crop the image prior to segment it. Args: ...
def segment_volume(folder_model, fname_image, fname_roi=None): """Segment an image. Segment an image (fname_image) using a pre-trained model (folder_model). If provided, a region of interest (fname_roi) is used to crop the image prior to segment it. Args: folder_model (string): foldername whic...
47,876
def generate(topology, topologyName, topologies_hdr, py_impl, cpp_impl): name = topologyName.replace('-', '_').replace('.', '_') # DLDT models come with multiple files foe different precision files = topology['files'] assert(len(files) > 0), topologyName if len(files) > 2: assert(topology['...
def generate(topology, topologyName, topologies_hdr, py_impl, cpp_impl): name = topologyName.replace('-', '_').replace('.', '_') # DLDT models come with multiple files foe different precision files = topology['files'] assert(len(files) > 0), topologyName if len(files) > 2: assert(topology['...
41,505
def test_qmu_tilde(caplog): mu = 1.0 pdf = pyhf.simplemodels.hepdata_like([6], [9], [3]) data = [9] + pdf.config.auxdata init_pars = pdf.config.suggested_init() par_bounds = pdf.config.suggested_bounds() par_bounds[pdf.config.poi_index] = [-10, 10] with caplog.at_level(logging.WARNING, 'pyh...
def test_qmu_tilde(caplog): mu = 1.0 pdf = pyhf.simplemodels.hepdata_like([6], [9], [3]) data = [9] + pdf.config.auxdata init_pars = pdf.config.suggested_init() par_bounds = pdf.config.suggested_bounds() par_bounds[pdf.config.poi_index] = [-10, 10] with caplog.at_level(logging.WARNING, 'pyh...
1,834
def _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters, fit_params, return_train_score=False, return_parameters=False, return_n_test_samples=False, return_times=False, return_estimator=False, error_score=np.nan): """Fi...
def _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters, fit_params, return_train_score=False, return_parameters=False, return_n_test_samples=False, return_times=False, return_estimator=False, error_score=np.nan): """Fi...
10,973
def from_env(name, default=NoDefaultValue, kind=str): """ Get a configuration value from the environment. Arguments --------- name : str The name of the environment variable to pull from for this setting. default : any A default value of the return type in case the inten...
def from_env(name, default=NoDefaultValue, kind=str): """ Get a configuration value from the environment. Arguments --------- name : str The name of the environment variable to pull from for this setting. default : any A default value of the return type in case the inten...
32,613
def cymru_bulk_whois_command(client: Client, args: Dict[str, Any]) -> List[CommandResults]: """ Returns results of 'cymru-bulk-whois' command :type client: ``Client`` :param Client: client to use :type args: ``Dict[str, Any]`` :param args: All command arguments - 'entry_id', 'delimiter' :re...
def cymru_bulk_whois_command(client: Client, args: Dict[str, Any]) -> List[CommandResults]: """ Returns results of 'cymru-bulk-whois' command :type client: ``Client`` :param Client: client to use :type args: ``Dict[str, Any]`` :param args: All command arguments - 'entry_id', 'delimiter' :re...
31,698
def fetch_last_emails(account, folder_name='Inbox', since_datetime=None, exclude_ids=None): qs = get_folder_by_path(account, folder_name, is_public=IS_PUBLIC_FOLDER) if since_datetime: qs = qs.filter(datetime_received__gte=since_datetime) else: if not FETCH_ALL_HISTORY: tz = EWS...
def fetch_last_emails(account, folder_name='Inbox', since_datetime=None, exclude_ids=None): qs = get_folder_by_path(account, folder_name, is_public=IS_PUBLIC_FOLDER) if since_datetime: qs = qs.filter(datetime_received__gte=since_datetime) else: if not FETCH_ALL_HISTORY: tz = EWS...
24,688
def get_available_rmw_implementations(): """ Return the set of all available RMW implementations as registered in the ament index. The result can be overridden by setting an environment variable named ``RMW_IMPLEMENTATIONS``. The variable can contain RMW implementation names separated by the platfo...
def get_available_rmw_implementations(): """ Return the set of all available RMW implementations as registered in the ament index. The result can be overridden by setting an environment variable named ``RMW_IMPLEMENTATIONS``. The variable can contain RMW implementation names separated by the platfo...
23,803
def set_dirty(folder): dirty_file = os.path.normpath(folder) + _DIRTY_FOLDER assert not os.path.exists(dirty_file) save(dirty_file, "")
def set_dirty(folder): dirty_file = os.path.normpath(folder) + _DIRTY_FOLDER assert not os.path.exists(dirty_file), "Folder '{}' is already dirty".format(folder) save(dirty_file, "")
37,337
def draw(program: Union[Waveform, ParametricPulse, Schedule], style: Optional[Dict[str, Any]] = None, backend: Optional[BaseBackend] = None, time_range_dt: Optional[Tuple[int, int]] = None, time_range_ns: Optional[Tuple[int, int]] = None, disable_channels: Optional[List[Puls...
def draw(program: Union[Waveform, ParametricPulse, Schedule], style: Optional[Dict[str, Any]] = None, backend: Optional[BaseBackend] = None, time_range_dt: Optional[Tuple[int, int]] = None, time_range_ns: Optional[Tuple[int, int]] = None, disable_channels: Optional[List[Puls...
16,341
def setup_platform(hass, config, add_entities, discovery_info=None): """Find and return switches controlled by shell commands.""" setup_reload_service(hass, DOMAIN, PLATFORMS) devices = config.get(CONF_SWITCHES, {}) switches = [] for object_id, device_config in devices.items(): icon_templ...
def setup_platform(hass, config, add_entities, discovery_info=None): """Find and return switches controlled by shell commands.""" setup_reload_service(hass, DOMAIN, PLATFORMS) devices = config.get(CONF_SWITCHES, {}) switches = [] for object_id, device_config in devices.items(): icon_templ...
17,398
def _get_engine_from_magic_number(filename_or_obj): # check byte header to determine file type if isinstance(filename_or_obj, bytes): magic_number = filename_or_obj[:8] else: if filename_or_obj.tell() != 0: raise ValueError( "file-like object read/write pointer no...
def _get_engine_from_magic_number(filename_or_obj): # check byte header to determine file type if isinstance(filename_or_obj, bytes): magic_number = filename_or_obj[:8] else: if filename_or_obj.tell() != 0: raise ValueError( "file-like object read/write pointer no...
6,819
def send_one(email, smtpserver=None, auto_commit=True, now=False, from_test=False): '''Send Email Queue with given smtpserver''' email = frappe.db.sql('''select name, status, communication, message, sender, reference_doctype, reference_name, unsubscribe_param, unsubscribe_method, expose_recipients, show_as_...
def send_one(email, smtpserver=None, auto_commit=True, now=False, from_test=False): '''Send Email Queue with given smtpserver''' email = frappe.db.sql('''select name, status, communication, message, sender, reference_doctype, reference_name, unsubscribe_param, unsubscribe_method, expose_recipients, show_as_...
5,261
def _extract_tokens(lemmas, scores, ratio, words): """Extracts tokens from provided lemmas. Most scored lemmas are used if `words` not provided. Parameters ---------- lemmas : list of str Given lemmas. scores : dict Dictionary with lemmas and its scores. ratio : float Pr...
def _extract_tokens(lemmas, scores, ratio, words): """Extracts tokens from provided lemmas. Most scored lemmas are used if `words` not provided. Parameters ---------- lemmas : list of str Given lemmas. scores : dict Dictionary with lemmas and its scores. ratio : float Pr...
48,412
def main(): module = AnsibleModule( argument_spec=dict( project_id=dict(required=True), instance_id=dict(required=True), ), supports_check_mode=True ) # Get parameters project_id = module.params.get('project_id') instance_id = module.params.get('insta...
def main(): module = AnsibleModule( argument_spec=dict( project_id=dict(required=True), instance_id=dict(required=True), ), supports_check_mode=True ) # Get parameters project_id = module.params.get('project_id') instance_id = module.params.get('insta...
8,244
def extract_along_coord(smap, coord): """ Return the value of the image array at every point along the coordinate. For a given coordinate ``coord``, find all the pixels that cross the coordinate and extract the values of the image array in ``smap`` at these points. This is done by applying `Bresenh...
def extract_along_coord(smap, coord): """ Return the value of the image array at every point along the coordinate. For a given coordinate ``coord``, find all the pixels that cross the coordinate and extract the values of the image array in ``smap`` at these points. This is done by applying `Bresenh...
17,695
def _push(dspath, content, target, data, force, jobs, res_kwargs, pbars, got_path_arg=False): force_git_push = force in ('all', 'gitpush') # nothing recursive in here, we only need a repo to work with ds = Dataset(dspath) repo = ds.repo res_kwargs.update(type='dataset', path=dspath) ...
def _push(dspath, content, target, data, force, jobs, res_kwargs, pbars, got_path_arg=False): force_git_push = force in ('all', 'gitpush') # nothing recursive in here, we only need a repo to work with ds = Dataset(dspath) repo = ds.repo res_kwargs.update(type='dataset', path=dspath) ...
54,061
def test_jumping_knowledge(): num_nodes, channels, num_layers = 100, 17, 5 xs = list([torch.randn(num_nodes, channels) for _ in range(num_layers)]) model = JumpingKnowledge('cat') assert model.__repr__() == 'JumpingKnowledge(cat)' out = model(xs) assert out.size() == (num_nodes, channels * num...
def test_jumping_knowledge(): num_nodes, channels, num_layers = 100, 17, 5 xs = list([torch.randn(num_nodes, channels) for _ in range(num_layers)]) model = JumpingKnowledge('cat') assert model.__repr__() == 'JumpingKnowledge(cat)' out = model(xs) assert out.size() == (num_nodes, channels * num...
43,920
def primitive_norm(l, alpha): r"""Compute the normalization constant for a primitive Gaussian function. A Gaussian function is defined as .. math:: G = x^l y^m z^n e^{-\alpha r^2}, where :math:`l = (l, m, n)` defines the angular momentum quantum numbers, :math:`\alpha` is the exponent an...
def primitive_norm(l, alpha): r"""Compute the normalization constant for a primitive Gaussian function. A Gaussian function is defined as .. math:: G = x^l y^m z^n e^{-\alpha r^2}, where :math:`l = (l, m, n)` defines the angular momentum quantum numbers, :math:`\alpha` is the exponent. T...
45,556
def update_auth(c, config): """ Set auth related configuration from YAML config file. As an example, this function should update the following TLJH auth configuration: ```yaml auth: type: oauthenticator.github.GitHubOAuthenticator GitHubOAuthenticator: client_id: "..." ...
def update_auth(c, config): """ Set auth related configuration from YAML config file. As an example, this function should update the following TLJH auth configuration: ```yaml auth: type: oauthenticator.github.GitHubOAuthenticator GitHubOAuthenticator: client_id: "..." ...
36,634
def install(domain, localedir=None, names=None): t = translation(domain, localedir, fallback=True) t.install(names)
def install(domain, localedir=None, *, names=None): t = translation(domain, localedir, fallback=True) t.install(names)
56,667
def sync_completed_sponsored_books(): from internetarchive import search_items params = {'page': 1, 'rows': 1000, 'scope': 'all'} fields = ['identifier', 'openlibrary_edition'] q = 'collection:openlibraryscanningteam AND collection:inlibrary' # XXX Note: This `search_items` query requires the `...
def sync_completed_sponsored_books(): from internetarchive import search_items # XXX Note: This `search_items` query requires the `ia` tool (the # one installed via virtualenv) to be configured with (scope:all) # privileged s3 keys. items = search_items( q='collection:openlibraryscanningteam...
40,609
def _test_model(model: Chainer, metrics_functions: List[Metric], iterator: DataLearningIterator, batch_size=-1, data_type='valid', start_time: float=None, show_examples=False) -> Dict[str, Union[int, OrderedDict, str]]: if start_time is None: start_time = time.time() exp...
def _test_model(model: Chainer, metrics_functions: List[Metric], iterator: DataLearningIterator, batch_size=-1, data_type='valid', start_time: float=None, show_examples=False) -> Dict[str, Union[int, OrderedDict, str]]: if start_time is None: start_time = time.time() exp...
2,375
def randomized_svd( M, n_components, *, n_oversamples=10, n_iter="auto", power_iteration_normalizer="auto", transpose="auto", flip_sign=True, random_state="warn", lapack_driver="gesdd" ): """Computes a truncated randomized SVD. This method solves the fixed-rank approxima...
def randomized_svd( M, n_components, *, n_oversamples=10, n_iter="auto", power_iteration_normalizer="auto", transpose="auto", flip_sign=True, random_state="warn", lapack_driver="gesdd" ): """Computes a truncated randomized SVD. This method solves the fixed-rank approxima...
56,733
def generate_samples(generator, *args, **kwargs): """Generate samples from the distribution of a random variable. Parameters ---------- generator: function Function to generate the random samples. The function is expected take parameters for generating samples and a keyword argu...
def generate_samples(generator, *args, **kwargs): """Generate samples from the distribution of a random variable. Parameters ---------- generator: function Function to generate the random samples. The function is expected take parameters for generating samples and a keyword argu...
14,677
def load_data(hass, url=None, filepath=None, username=None, password=None, authentication=None, num_retries=5, verify_ssl=None): """Load data into ByteIO/File container from a source.""" try: if url is not None: # Load data from URL params = {"timeout": 15} ...
def load_data(hass, url=None, filepath=None, username=None, password=None, authentication=None, num_retries=5, verify_ssl=None): """Load data into ByteIO/File container from a source.""" try: if url is not None: # Load data from URL params = {"timeout": 15} ...
57,608
def fetch_exchange(zone_key1='CR', zone_key2='PA', session=None, target_datetime=None, logger=logging.getLogger(__name__)) -> dict: """ Requests the last known power exchange (in MW) between two countries. """ if target_datetime: raise NotImplementedError( 'This p...
def fetch_exchange(zone_key1='CR', zone_key2='PA', session=None, target_datetime=None, logger=logging.getLogger(__name__)) -> dict: """ Requests the last known power exchange (in MW) between two countries. """ if target_datetime: raise NotImplementedError("This parser is not ...
46,205
def imread(filename: str): """custom imaplementation of imread to avoid skimage dependecy""" ext = os.path.splitext(filename)[1] if ext in [".tif", "tiff", ".lsm"]: import tifffile image = tifffile.imread(filename) else: import imageio image = imageio.imread(filename) ...
def imread(filename: str): """custom imaplementation of imread to avoid skimage dependecy""" ext = os.path.splitext(filename)[1] if ext in [".tif", ".tiff", ".lsm"]: import tifffile image = tifffile.imread(filename) else: import imageio image = imageio.imread(filename) ...
15,136
def test_deprecated_with_replacement_key(caplog, schema): """ Test deprecation behaves correctly when only a replacement key is provided. Expected behavior: - Outputs the appropriate deprecation warning if key is detected - Processes schema moving the value from key to replacement_key ...
def test_deprecated_with_replacement_key(caplog, schema): """ Test deprecation behaves correctly when only a replacement key is provided. Expected behavior: - Outputs the appropriate deprecation warning if key is detected - Processes schema moving the value from key to replacement_key ...
4,284
def _make_rename_map(chs): orig_ch_names = [c['ch_name'] for c in chs] ch_names = orig_ch_names.copy() _unique_channel_names(ch_names, max_length=15, verbose='error') rename_map = dict() if orig_ch_names != ch_names: rename_map.update(zip(orig_ch_names, ch_names)) return rename_map
def _make_ch_names_mapping(chs): orig_ch_names = [c['ch_name'] for c in chs] ch_names = orig_ch_names.copy() _unique_channel_names(ch_names, max_length=15, verbose='error') rename_map = dict() if orig_ch_names != ch_names: rename_map.update(zip(orig_ch_names, ch_names)) return rename_map...
30,676
def update_server_configuration(client, server_configuration, error_msg): """updates server configuration Args: client (demisto_client): The configured client to use. server_configuration (dict): The server configuration to be added error_msg (str): The error message Returns: ...
def update_server_configuration(client, server_configuration, error_msg): """updates server configuration Args: client (demisto_client): The configured client to use. server_configuration (dict): The server configuration to be added error_msg (str): The error message Returns: ...
26,188
def call_auth_api(integrationToken): # Get API key try: response = requests.get(AUTH_API_URL + '?token=' + integrationToken) except requests.exceptions.Timeout: raise CheckException('Failed to get API key by timeout') except Exception as e: raise CheckException('Failed to get API...
def call_auth_api(integrationToken): # Get API key try: response = self.http.get(AUTH_API_URL + '?token=' + integrationToken) except requests.exceptions.Timeout: raise CheckException('Failed to get API key by timeout') except Exception as e: raise CheckException('Failed to get AP...
58,558
def connected_context_num(): global _lock, _all_contexts with _lock: return len(_all_contexts)
def num_connected_contexts(): """Return the number of client connections active.""" global _lock, _all_contexts with _lock: return len(_all_contexts)
40,255
def main(): parser = create_parser( description=HELP_TEXT, logfilename='gvm-pyshell.log') parser.add_protocol_argument() parser.add_argument( '-i', '--interactive', action='store_true', default=False, help='Start an interactive Python shell') parser.add_argument( 'scri...
def main(): parser = create_parser( description=HELP_TEXT, logfilename='gvm-pyshell.log') parser.add_protocol_argument() parser.add_argument( '-i', '--interactive', action='store_true', default=False, help='Start an interactive Python shell') parser.add_argument( 'scri...
7,913
def test_external_mesh(cpp_driver): ### Materials ### materials = openmc.Materials() fuel_mat = openmc.Material(name="fuel") fuel_mat.add_nuclide("U235", 1.0) fuel_mat.set_density('g/cc', 4.5) materials.append(fuel_mat) zirc_mat = openmc.Material(name="zircaloy") zirc_mat.add_element(...
def test_external_mesh(cpp_driver): ### Materials ### materials = openmc.Materials() fuel_mat = openmc.Material(name="fuel") fuel_mat.add_nuclide("U235", 1.0) fuel_mat.set_density('g/cc', 4.5) materials.append(fuel_mat) zirc_mat = openmc.Material(name="zircaloy") zirc_mat.add_element(...
1,091
def generate_boutiques_descriptor( module, interface_name, container_image, container_type, container_index=None, verbose=False, save=False, save_path=None, author=None, ignore_inputs=None, tags=None): ''' Returns a JSON string containing a JSON Boutiques description of a Nipype interface. A...
def generate_boutiques_descriptor( module, interface_name, container_image, container_type, container_index=None, verbose=False, save=False, save_path=None, author=None, ignore_inputs=None, tags=None): ''' Returns a JSON string containing a JSON Boutiques description of a Nipype interface. A...
33,967
def _batch_args_kwargs( list_of_flatten_args: List[List[Any]], ) -> Tuple[Tuple[Any], Dict[Any, Any]]: """Batch a list of flatten args and returns regular args and kwargs""" # Ray's flatten arg format is a list with alternating key and values # e.g. args=(1, 2), kwargs={"key": "val"} got turned into ...
def _batch_args_kwargs( list_of_flattened_args: List[List[Any]], ) -> Tuple[Tuple[Any], Dict[Any, Any]]: """Batch a list of flatten args and returns regular args and kwargs""" # Ray's flatten arg format is a list with alternating key and values # e.g. args=(1, 2), kwargs={"key": "val"} got turned into ...
29,900
def start_prometheus_exporter_sidecar() -> None: port = os.environ.get("BASEPLATE_SIDECAR_ADMIN_PORT") endpoint = Endpoint("0.0.0.0:" + port) start_prometheus_exporter(endpoint)
def start_prometheus_exporter_for_sidecar() -> None: port = os.environ.get("BASEPLATE_SIDECAR_ADMIN_PORT") endpoint = Endpoint("0.0.0.0:" + port) start_prometheus_exporter(endpoint)
9,510
def main(): module = AnsibleModule( argument_spec=dict( host=dict(type='str', required=True), login=dict(type='str', default='Administrator'), password=dict(type='str', default='admin', no_log=True), ssl_version=dict(type='str', default='TLSv1', choices=['SSL...
def main(): module = AnsibleModule( argument_spec=dict( host=dict(type='str', required=True), login=dict(type='str', default='Administrator'), password=dict(type='str', default='admin', no_log=True), ssl_version=dict(type='str', default='TLSv1', choices=['SSL...
13,523
def parse_value_name_collumn(value_name, value, signal_size, float_factory): mini = maxi = offset = None value_table = dict() if ".." in value_name: (mini, maxi) = value_name.strip().split("..", 2) mini = float_factory(mini) maxi = float_factory(maxi) offset = mini elif ...
def parse_value_name_column(value_name, value, signal_size, float_factory): mini = maxi = offset = None value_table = dict() if ".." in value_name: (mini, maxi) = value_name.strip().split("..", 2) mini = float_factory(mini) maxi = float_factory(maxi) offset = mini elif v...
34,056
def record_extra_usage_tag(key: str, value: str): """Record extra kv usage tag. If the key already exists, the value will be overwritten. Caller should make sure the uniqueness of the key to avoid conflicts. It will make a synchronous call to the internal kv store. """ if _recorded_extra_usage...
def record_extra_usage_tag(key: str, value: str): """Record extra kv usage tag. If the key already exists, the value will be overwritten. Caller should make sure the uniqueness of the key to avoid conflicts. It will make a synchronous call to the internal kv store if the tag is updated. """ if...
45,307
def train( params: Dict, dtrain: DMatrix, *args, evals=(), num_actors: Optional[int] = None, evals_result: Optional[Dict] = None, **kwargs, ): """Run distributed training of XGBoost model. During work it evenly distributes `dtrain` between workers according to IP addresses parti...
def train( params: Dict, dtrain: DMatrix, *args, evals=(), num_actors: Optional[int] = None, evals_result: Optional[Dict] = None, **kwargs, ): """Run distributed training of XGBoost model. During work it evenly distributes `dtrain` between workers according to IP addresses parti...
30,589
def parse_url(item: str) -> str: """ Parse url if in url form to valid EDL form - withouth http / https Args: item(str): Item to parse. Returns: str: parsed item, if URL returned without http / https Examples: >>> parse_url('http://google.com') 'google.com' >>>...
def parse_url(item: str) -> str: """ Parse url if in url form to valid EDL form - without http / https Args: item(str): Item to parse. Returns: str: parsed item, if URL returned without http / https Examples: >>> parse_url('http://google.com') 'google.com' >>> ...
17,194
def _convert_states(states: dict[str, Any]) -> dict[str, Any]: """Convert state definitions to State objects.""" result = {} for entity_id, info in states.items(): entity_id = cv.entity_id(entity_id) if isinstance(info, dict): entity_attrs = info.copy() state = enti...
def _convert_states(states: dict[str, Any]) -> dict[str, State]: """Convert state definitions to State objects.""" result = {} for entity_id, info in states.items(): entity_id = cv.entity_id(entity_id) if isinstance(info, dict): entity_attrs = info.copy() state = en...
30,339
def get_group_tags(): """ Retrieve the Tags for a Group """ group_type = demisto.args().get('group_type') group_id = int(demisto.args().get('group_id')) contents = [] context_entries = [] response = get_group_tags_request(group_type, group_id) data = response.get('data', {}).get('tag...
def get_group_tags(): """ Retrieve the Tags for a Group """ group_type = demisto.args().get('group_type') group_id = int(demisto.args().get('group_id')) contents = [] context_entries = [] response = get_group_tags_request(group_type, group_id) data = response.get('data', {}).get('tag...
24,517
def main( input_d, output_d, reject_d, extension=None, fheight=500, fwidth=500, facePercent=50, no_resize=False, ): """Crops folder of images to the desired height and width if a face is found. If `input_d == output_d` or `output_d is None`, overwrites all files where the biggest face was found. ...
def main( input_d, output_d, reject_d, extension=None, fheight=500, fwidth=500, facePercent=50, no_resize=False, ): """Crops folder of images to the desired height and width if a face is found. If `input_d == output_d` or `output_d is None`, overwrites all files where the biggest face was found. ...
56,668
def get_sponsored_books(): """Performs the `ia` query to fetch sponsored books from archive.org""" from internetarchive import search_items params = {'page': 1, 'rows': 1000, 'scope': 'all'} fields = ['identifier','est_book_price','est_scan_price', 'scan_price', 'book_price', 'repub_state'...
def get_sponsored_books(): """Performs the `ia` query to fetch sponsored books from archive.org""" from internetarchive import search_items params = {'page': 1, 'rows': 1000, 'scope': 'all'} fields = ['identifier','est_book_price','est_scan_price', 'scan_price', 'book_price', 'repub_state'...
35,101
def test_load_late_bound_consts_with_no_late_bound_consts(): """Check that load_late_bound_consts handles a model with no late bound consts.""" target = tvm.target.Target("llvm") const_data = np.random.rand(1).astype("float64") x = relay.var("x", shape=(1,), dtype="float64") const = relay.const(con...
def test_load_late_bound_consts_with_no_late_bound_consts(): """Check that load_late_bound_consts handles a model with no late bound consts.""" target = tvm.target.Target("llvm") const_data = np.random.rand(1).astype("float64") x = relay.var("x", shape=(1,), dtype="float64") const = relay.const(con...
37,813
def execute_cmd( docker: DockerContainer, cmd_str: str, before_build: bool, target_arch: str, env: Optional[Dict[str, str]] = None, ) -> None: invalid_cmd = False pip_install_env_create = True tmpdirpath = "" assert env is not None target_arch_env = TargetArchEnvUtil(env.get("CR...
def execute_cmd( docker: DockerContainer, cmd_str: str, before_build: bool, target_arch: str, env: Optional[Dict[str, str]] = None, ) -> None: invalid_cmd = False pip_install_env_create = True tmpdirpath = "" assert env is not None target_arch_env = TargetArchEnvUtil(env.get("CR...
48,783
def _run_task_by_executor(args, dag, ti): """ Sends the task to the executor for execution. This can result in the task being started by another host if the executor implementation does """ pickle_id = None if args.ship_dag: try: # Running remotely, so pickling the DAG ...
def _run_task_by_executor(args, dag, ti): """ Sends the task to the executor for execution. This can result in the task being started by another host if the executor implementation does """ pickle_id = None if args.ship_dag: try: # Running remotely, so pickling the DAG ...
33,986
def _inject_ray_to_conda_site( conda_path, logger: Optional[logging.Logger] = default_logger ): """Write the current Ray site package directory to a new site""" if _WIN32: python_binary = os.path.join(conda_path, "python") else: python_binary = os.path.join(conda_path, "bin/python") ...
def _inject_ray_to_conda_site( conda_path, logger: Optional[logging.Logger] = default_logger ): """Write the current Ray site package directory to a new site""" if _WIN32: python_binary = os.path.join(conda_path, "python") else: python_binary = os.path.join(conda_path, "bin/python") ...
57,373
def _update_yaml_with_extracted_metadata( config_data: Dict[str, Any], parts_config: project_loader.PartsConfig, prime_dir: str, ) -> extractors.ExtractedMetadata: if "adopt-info" in config_data: part_name = config_data["adopt-info"] part = parts_config.get_part(part_name) if not...
def _update_yaml_with_extracted_metadata( config_data: Dict[str, Any], parts_config: project_loader.PartsConfig, prime_dir: str, ) -> extractors.ExtractedMetadata: if "adopt-info" not in config_data: return None part_name = config_data["adopt-info"] part = parts_config.get_part(p...
44,839
def _add_code_to_system_path(code_path): sys.path = [code_path] + _get_code_dirs(code_path) + sys.path # delete code modules that are already in sys.modules # so they will get reloaded anew from the correct code path # othterwise python will use the alredy loaded modules modules = [] for path ...
def _add_code_to_system_path(code_path): sys.path = [code_path] + _get_code_dirs(code_path) + sys.path # delete code modules that are already in sys.modules # so they will get reloaded anew from the correct code path # otherwise python will use the already loaded modules modules = [] for path ...
4,214
def test_read_write_info(tmpdir): """Test IO of info.""" info = read_info(raw_fname) temp_file = str(tmpdir.join('info.fif')) # check for bug `#1198` info['dev_head_t']['trans'] = np.eye(4) t1 = info['dev_head_t']['trans'] write_info(temp_file, info) info2 = read_info(temp_file) t2 =...
def test_read_write_info(tmpdir): """Test IO of info.""" info = read_info(raw_fname) temp_file = str(tmpdir.join('info.fif')) # check for bug `#1198` info['dev_head_t']['trans'] = np.eye(4) t1 = info['dev_head_t']['trans'] write_info(temp_file, info) info2 = read_info(temp_file) t2 =...
39,411
def get_cmap_safe(cmap): """Fetch a colormap by name from matplotlib, colorcet, or cmocean.""" try: from matplotlib.cm import get_cmap except ImportError: raise ImportError('The use of custom colormaps requires the installation of matplotlib') if isinstance(cmap, str): # check i...
def get_cmap_safe(cmap): """Fetch a colormap by name from matplotlib, colorcet, or cmocean.""" try: from matplotlib.cm import get_cmap except ImportError: raise ImportError('The use of custom colormaps requires the installation of matplotlib') if isinstance(cmap, str): # check i...
32,240
def reboot(topology: Topology, hostid: str) -> RestartSystemCommandResult: """ Reboot the given host. :param topology: `Topology` instance !no-auto-argument :param hostid: ID of host (serial or hostname) to reboot """ result: RestartSystemCommandResult = UniversalCommand.reboot(topology, hostid...
def reboot(topology: Topology, hostid: str) -> RestartSystemCommandResult: """ Reboot the given host. :param topology: `Topology` instance !no-auto-argument :param hostid: ID of host (serial or hostname) to reboot """ return UniversalCommand.reboot(topology, hostid=hostid)
7,529
def sigma_clipped_stats(data, mask=None, mask_value=None, sigma=3.0, sigma_lower=None, sigma_upper=None, maxiters=5, cenfunc='median', stdfunc='std', std_ddof=0, axis=None, grow=False): """ Calculate sigma-clipped statistics on the provided...
def sigma_clipped_stats(data, mask=None, mask_value=None, sigma=3.0, sigma_lower=None, sigma_upper=None, maxiters=5, cenfunc='median', stdfunc='std', std_ddof=0, axis=None, grow=False): """ Calculate sigma-clipped statistics on the provided...
50,677
def _load_audio_single(file_path, return_pts_based_timestamps=False): try: container = av.open(str(file_path)) stream = next(iter(container.streams.audio)) logger.debug("Loaded audiostream: %s" % stream) except (av.AVError, StopIteration): return None ts_path = file_path.wit...
def _load_audio_single(file_path, return_pts_based_timestamps=False): try: container = av.open(str(file_path)) stream = next(iter(container.streams.audio)) logger.debug("Loaded audiostream: %s" % stream) except (av.AVError, StopIteration): return None ts_path = file_path.wit...
32,099
def status_get_command(args, is_polling=False): request_ids_for_polling = {} request_ids = argToList(args.get('request_ids')) timeout = args.get('timeout') timeout_duration = args.get('timeout_duration') timeout = timeout and int(timeout) responses = [] files_output = [] file_standard_...
def status_get_command(args, is_polling=False): request_ids_for_polling = {} request_ids = argToList(args.get('request_ids')) timeout = args.get('timeout') timeout_duration = args.get('timeout_duration') timeout = timeout and int(timeout) responses = [] files_output = [] file_standard_...
52,227
def _prepare_certificate_signing_request(domain, key_file, output_folder): from OpenSSL import crypto # lazy loading this module for performance reasons # Init a request csr = crypto.X509Req() # Set the domain csr.get_subject().CN = domain # Include xmpp-upload subdomain in subject alternate ...
def _prepare_certificate_signing_request(domain, key_file, output_folder): from OpenSSL import crypto # lazy loading this module for performance reasons # Init a request csr = crypto.X509Req() # Set the domain csr.get_subject().CN = domain from yunohost.domain import domain_list # For "pa...
42,984
def apply_twomode_gate(mat, state, pure, modes, n, trunc, gate="BSgate"): """Applies a two-mode gate to a state Applies the two-mode gate to the state using custom tensor contractions and the numba compiler for faster application. Args: mat (ndarray): The BS operator to be applied to the state...
def apply_twomode_gate(mat, state, pure, modes, n, trunc, gate="BSgate"): """Applies a two-mode gate to a state. Applies the two-mode gate to the state using custom tensor contractions and the numba compiler for faster application. Args: mat (ndarray): The BS operator to be applied to the stat...
59,186
def dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) return wraps(func)(wrapper)
def dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) return wraps(func)(wrapper)
49,609
def add_path_column(df, column_name, path, dtype): if column_name in df.columns: raise ValueError( f"Files already contain the column name: '{column_name}', so the path " "column cannot use this name. Please set `include_path_column` to a " "`include_path_column` to a uni...
def add_path_column(df, column_name, path, dtype): if column_name in df.columns: raise ValueError( f"Files already contain the column name: '{column_name}', so the path " "column cannot use this name. Please set `include_path_column` to a " "unique name." ) re...
23,112
def set_partitions_pre(s, divisions, ascending=True): try: if ascending: partitions = divisions.searchsorted(s, side="right") - 1 else: partitions = -divisions.searchsorted(s, side="right") % (len(divisions) - 1) except TypeError: # When `searchsorted` fails with ...
def set_partitions_pre(s, divisions, ascending=True): try: if ascending: partitions = divisions.searchsorted(s, side="right") - 1 else: partitions = len(divisions) - divisions.searchsorted(s, side="right") - 1 except TypeError: # When `searchsorted` fails with `Ty...
4,177
def _check_full_data(inst, full_data): """Check whether data is represented as kernel or not.""" if full_data: assert isinstance(inst._kernel, type(None)) assert isinstance(inst._sens_data, type(None)) assert isinstance(inst._data, np.ndarray) else: assert isinstance(inst._ke...
def _check_full_data(inst, full_data): """Check whether data is represented as kernel or not.""" if full_data: assert inst._kernel is None assert isinstance(inst._sens_data, type(None)) assert isinstance(inst._data, np.ndarray) else: assert isinstance(inst._kernel, np.ndarray...
7,894
def _vectfit_xs(energy, ce_xs, mts, rtol=1e-3, atol=1e-5, orders=None, n_vf_iter=30, log=False, path_out=None, **kwargs): r"""Convert point-wise cross section to multipole data via Vector Fitting. Parameters ---------- energy : np.ndarray Energy array ce_xs : np.ndarray ...
def _vectfit_xs(energy, ce_xs, mts, rtol=1e-3, atol=1e-5, orders=None, n_vf_iter=30, log=False, path_out=None, **kwargs): r"""Convert point-wise cross section to multipole data via Vector Fitting. Parameters ---------- energy : np.ndarray Energy array ce_xs : np.ndarray ...
43,567
def DisplacementEmbedding(features, wires, method='amplitude', c=0.1): r"""Encodes :math:`N` features into the displacement amplitudes :math:`r` or phases :math:`\phi` of :math:`M` modes, where :math:`N\leq M`. The mathematical definition of the displacement gate is given by the operator .. math:: ...
def DisplacementEmbedding(features, wires, method='amplitude', c=0.1): r"""Encodes :math:`N` features into the displacement amplitudes :math:`r` or phases :math:`\phi` of :math:`M` modes, where :math:`N\leq M`. The mathematical definition of the displacement gate is given by the operator .. math:: ...
55,471
def run_deployment( deployment_name: str, max_polls: int = 60, poll_interval: float = 5, parameters: dict = None, ): """ Runs a deployment immediately. This function will block until the deployment run enters a terminal state or until the polling duration has been exceeded. """ ...
def run_deployment( deployment_name: str, max_polls: int = 60, poll_interval: float = 5, parameters: dict = None, ): """ Runs a deployment immediately. This function will block until the deployment run enters a terminal state or until the polling duration has been exceeded. If max_polls...
54,262
def get_editor() -> Optional[List[str]]: editor_line = os.environ.get('VISUAL') or os.environ.get('EDITOR') if editor_line: return editor_line.split(' ') for editor in ('vim', 'nano', 'mcedit', 'edit', 'emacs', 'e3', 'atom', 'adie', 'dedit', 'gedit', 'jedit', 'kate', 'kwrite', 'leafpad', 'mousepad',...
def get_editor() -> Optional[List[str]]: editor_line = os.environ.get('VISUAL') or os.environ.get('EDITOR') if editor_line: return editor_line.split(' ') for editor in ( 'vim', 'nano', 'mcedit', 'edit', 'emacs', 'e3', 'atom', 'adie', 'dedit', 'gedit', 'jedit', 'kate', 'kwrite...
30,808
def update_user_command(client, args): """ Update user using PUT to Envoy API , if Connection to the service is successful. Args: demisto command line argument client: Envoy Returns: success : success=True, id, email, login as username, details, active status ...
def update_user_command(client, args): """ Update user using PUT to Envoy API , if Connection to the service is successful. Args: demisto command line argument client: Envoy Returns: success : success=True, id, email, login as username, details, active status ...
31,435
def main(): try: args = demisto.args() pwd_generation_script = args.get("pwdGenerationScript") username = args.get("sAMAccountName") user_email = args.get("email") display_name = args.get("displayname") to_email = args.get("to_email") # Generate a random pass...
def main(): try: args = demisto.args() pwd_generation_script = args.get("pwdGenerationScript") username = args.get("sAMAccountName") user_email = args.get("email") display_name = args.get("displayname") to_email = args.get("to_email") # Generate a random pass...
17,459
def test_dataset_groupby(): data = Dataset( {"z": (["x", "y"], np.random.randn(3, 5))}, {"x": ("x", list("abc")), "c": ("x", [0, 1, 0]), "y": range(5)}, ) groupby = data.groupby("x") assert len(groupby) == 3 expected_groups = {"a": 0, "b": 1, "c": 2} assert groupby.groups == expe...
def test_groupby_dataset(): data = Dataset( {"z": (["x", "y"], np.random.randn(3, 5))}, {"x": ("x", list("abc")), "c": ("x", [0, 1, 0]), "y": range(5)}, ) groupby = data.groupby("x") assert len(groupby) == 3 expected_groups = {"a": 0, "b": 1, "c": 2} assert groupby.groups == expe...
52,276
def get_parser(): # Initialize the parser parser = argparse.ArgumentParser( description=( "This program segments automatically the spinal cord on T1- and T2-weighted images, for any field of view. " "You must provide the type of contrast, the image as well as the output folder pa...
def get_parser(): # Initialize the parser parser = argparse.ArgumentParser( description=( "This program segments automatically the spinal cord on T1- and T2-weighted images, for any field of view. " "You must provide the type of contrast, the image as well as the output folder pa...
20,537
def func_median(data, mask=None, map_clusters=None): """ Compute weighted median. Code inspired from: https://gist.github.com/tinybike/d9ff1dad515b66cc0d87 :param data: nd-array: input data :param mask: (n+1)d-array: input mask :param map_clusters: not used :return: """ # Check if ma...
def func_median(data, mask=None, map_clusters=None): """ Compute weighted median. Code inspired from: https://gist.github.com/tinybike/d9ff1dad515b66cc0d87 :param data: nd-array: input data :param mask: (n+1)d-array: input mask :param map_clusters: not used :return: """ # Check if ma...
6,412
def invoice_appointment(appointment_doc): automate_invoicing = frappe.db.get_single_value('Healthcare Settings', 'automate_appointment_invoicing') appointment_invoiced = frappe.db.get_value('Patient Appointment', appointment_doc.name, 'invoiced') enable_free_follow_ups = frappe.db.get_single_value('Healthcare Settin...
def invoice_appointment(appointment_doc): automate_invoicing = frappe.db.get_single_value('Healthcare Settings', 'automate_appointment_invoicing') appointment_invoiced = frappe.db.get_value('Patient Appointment', appointment_doc.name, 'invoiced') enable_free_follow_ups = frappe.db.get_single_value('Healthcare Settin...
40,544
def get_custom_locations_oid(cmd, cl_oid): try: sp_graph_client = get_graph_client_service_principals(cmd.cli_ctx) sub_filters = [] sub_filters.append("displayName eq '{}'".format("Custom Locations RP")) result = list(sp_graph_client.list(filter=(' and '.join(sub_filters)))) ...
def get_custom_locations_oid(cmd, cl_oid): try: sp_graph_client = get_graph_client_service_principals(cmd.cli_ctx) sub_filters = [] sub_filters.append("displayName eq '{}'".format("Custom Locations RP")) result = list(sp_graph_client.list(filter=(' and '.join(sub_filters)))) ...
31,523
def get_report_command(args: dict): """ pingcastle-get-report command: Returns the last report sent by PingCastle Args: args (dict): A dict object containing the arguments for this command """ delete_report = args.get('delete_report') == 'Yes' context = demisto.getIntegrationContext() ...
def get_report_command(args: dict): """ pingcastle-get-report command: Returns the last report sent by PingCastle Args: args (dict): A dict object containing the arguments for this command """ delete_report = args.get('delete_report') == 'Yes' context = get_integration_context() repo...
1,358
def plot_dendrogram(model, **kwargs): # Create linkage matrix and then plot the dendrogram # create the counts of samples in each node counts = np.zeros(model.children_.shape[0]) n_samples = len(model.labels_) for i, merge in enumerate(model.children_): current_count = 0 for j in [0...
def plot_dendrogram(model, **kwargs): # Create linkage matrix and then plot the dendrogram # create the counts of samples under each node counts = np.zeros(model.children_.shape[0]) n_samples = len(model.labels_) for i, merge in enumerate(model.children_): current_count = 0 for j in...
27,876
def n_step_gru( n_layers, dropout_ratio, hx, ws, bs, xs, **kwargs): """n_step_gru(n_layers, dropout_ratio, hx, ws, bs, xs) Stacked Uni-directional Gated Recurrent Unit function. This function calculates stacked Uni-directional GRU with sequences. This function gets an initial hidden state :mat...
def n_step_gru( n_layers, dropout_ratio, hx, ws, bs, xs, **kwargs): """n_step_gru(n_layers, dropout_ratio, hx, ws, bs, xs) Stacked Uni-directional Gated Recurrent Unit function. This function calculates stacked Uni-directional GRU with sequences. This function gets an initial hidden state :mat...
24,867
def do_somtest_finds_short_name_exceptionething(): """Do something. Raises: ~fake_package.exceptions.BadError: When something bad happened. """ raise BadError("A bad thing happened.")
def test_finds_short_name_exception(): """Do something. Raises: ~fake_package.exceptions.BadError: When something bad happened. """ raise BadError("A bad thing happened.")
47,474
def main(): args = parse_args() # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. # If we're using tracking, we also need to initialize it here and it will pick up all supported trackers in the environment if args.with_tracking: accelerato...
def main(): args = parse_args() # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. # If we're using tracking, we also need to initialize it here and it will pick up all supported trackers in the environment accelerator = Accelerator(log_with="all")...
12,470
def _determine_eq_order(ctx: 'mypy.plugin.ClassDefContext') -> bool: """ Validate the combination of *cmp*, *eq*, and *order*. Derive the effective value of order. """ cmp = _get_decorator_optional_bool_argument(ctx, 'cmp') eq = _get_decorator_optional_bool_argument(ctx, 'eq') order = _get_d...
def _determine_eq_order(ctx: 'mypy.plugin.ClassDefContext') -> bool: """ Validate the combination of *cmp*, *eq*, and *order*. Derive the effective value of order. """ cmp = _get_decorator_optional_bool_argument(ctx, 'cmp') eq = _get_decorator_optional_bool_argument(ctx, 'eq') order = _get_d...
172
def upgrade(): """Add a new Bool column to bugs table, set default to False.""" op.add_column('bugs', sa.Column('private', sa.Boolean(), nullable=True)) op.execute("""UPDATE bugs SET private = FALSE""") op.alter_column('bugs', 'private', nullable=False, server_default='false')
def upgrade(): """Add a new Bool column to bugs table, set default to False.""" op.add_column('bugs', sa.Column('private', sa.Boolean(), nullable=True)) op.execute("""UPDATE bugs SET private = FALSE""") op.alter_column('bugs', 'private', nullable=False)
57,660
def list_workers_command(client: Client, args: dict) -> CommandResults: count = int(args.get('count', "1")) page = int(args.get('page', "1")) num_of_managers = int(args.get('managers', "3")) employee_id = args.get('employee_id') raw_json_response, workers_data = client.list_workers(page, count, empl...
def list_workers_command(client: Client, args: dict) -> CommandResults: count = int(args.get('count', '1')) page = int(args.get('page', '1')) num_of_managers = int(args.get('managers', '3')) employee_id = args.get('employee_id') raw_json_response, workers_data = client.list_workers(page, count, empl...
59,523
def _write_instruction(file_obj, instruction_tuple, custom_instructions, index_map): gate_class_name = instruction_tuple[0].__class__.__name__ if ( ( not hasattr(library, gate_class_name) and not hasattr(circuit_mod, gate_class_name) and not hasattr(extensions, gate_c...
def _write_instruction(file_obj, instruction_tuple, custom_instructions, index_map): gate_class_name = instruction_tuple[0].__class__.__name__ if ( ( not hasattr(library, gate_class_name) and not hasattr(circuit_mod, gate_class_name) and not hasattr(extensions, gate_c...
35,385
def process_measurement_list(lines, lists=None, m2w=None, pcrval=None): errs = [0, 0, 0, 0] runninghash = START_HASH found_pcr = (pcrval == None) if lists is not None: lists = ast.literal_eval(lists) whitelist = lists['whitelist'] exclude_list = lists['exclude'] else: ...
def process_measurement_list(lines, lists=None, m2w=None, pcrval=None): errs = [0, 0, 0, 0] runninghash = START_HASH found_pcr = (pcrval == None) if lists is not None: lists = ast.literal_eval(lists) whitelist = lists['whitelist'] exclude_list = lists['exclude'] else: ...
31,137
def url_quota_command(): cmd_url = '/urlCategories/urlQuota' response = http_request('GET', cmd_url).json() human_readable = { 'Unique Provisioned URLs': response.get('uniqueUrlsProvisioned'), 'Remaining URLs Quota': response.get('remainingUrlsQuota') } entry = { 'Type': ent...
def url_quota_command(): cmd_url = '/urlCategories/urlQuota' response = http_request('GET', cmd_url).json() human_readable = { 'Unique Provisioned URLs': response.get('uniqueUrlsProvisioned'), 'Remaining URLs Quota': response.get('remainingUrlsQuota'), } entry = { 'Type': en...
57,730
def get_duo_admin_by_name(name): duo_administrators = admin_api.get_admins() duo_administrator = next((admin for admin in duo_administrators if admin['name'] == name), None) entry = get_entry_for_object( 'Information about admin ' + name, duo_administrator, duo_administrator, { ...
def get_duo_admin_by_name(name): duo_administrators = admin_api.get_admins() duo_administrator = next((admin for admin in duo_administrators if admin['name'] == name), None) entry = get_entry_for_object( 'Information about admin ' + name, duo_administrator, duo_administrator, { ...
21,948
def lqe(*args, **keywords): """lqe(A, G, C, Q, R, [, N]) Linear quadratic estimator design (Kalman filter) for continuous-time systems. Given the system .. math:: x &= Ax + Bu + Gw \\\\ y &= Cx + Du + v with unbiased process noise w and measurement noise v with covariances ....
def lqe(*args, **keywords): """lqe(A, G, C, Q, R, [, N]) Linear quadratic estimator design (Kalman filter) for continuous-time systems. Given the system .. math:: x &= Ax + Bu + Gw \\\\ y &= Cx + Du + v with unbiased process noise w and measurement noise v with covariances ....
34,183
def create_dir_for_file(file_path: Text) -> None: """Creates any missing parent directories of this files path.""" try: os.makedirs(os.path.dirname(file_path)) except OSError as e: # be happy if someone already created the path if e.errno != errno.EEXIST: raise
def create_directory_for_file(file_path: Text) -> None: """Creates any missing parent directories of this files path.""" try: os.makedirs(os.path.dirname(file_path)) except OSError as e: # be happy if someone already created the path if e.errno != errno.EEXIST: raise
40,252
def meshgrid(x, y, indexing='xy'): """Construct coordinate matrices from two coordinate vectors. Parameters ---------- x : list[float] The values of the "x axis" of the grid. y : list[float] The values of the "y axis" of the grid. indexing : {'xy', 'ij'}, optional The in...
def meshgrid(x, y, indexing='xy'): """Construct coordinate matrices from two coordinate vectors. Parameters ---------- x : list[float] The values of the "x axis" of the grid. y : list[float] The values of the "y axis" of the grid. indexing : {'xy', 'ij'}, optional The in...
38,062
def _load_static_earth_relief(**kwargs): """ Load the static_earth_relief file for internal testing. Returns ------- data : xarray.DataArray A grid of Earth relief for internal tests. """ fname = which("@static_earth_relief.nc", download="c") data = xr.open_dataarray(fname) ...
def _load_static_earth_relief(**kwargs): """ Load the static_earth_relief file for internal testing. Returns ------- data : xarray.DataArray A grid of Earth relief for internal tests. """ fname = which("@static_earth_relief.nc", download="c") return xr.open_dataarray(fname)
59,163
def test_read_visium_counts(): # Test that checks the read_visium function h5_pth = ROOT / '../visium_data/1.0.0' spec_genome_v3 = sc.read_visium(h5_pth, genome='GRCh38') nospec_genome_v3 = sc.read_visium(h5_pth) assert_anndata_equal(spec_genome_v3, nospec_genome_v3)
def test_read_visium_counts(): # Test that checks the read_visium function visium_pth = ROOT / '../visium_data/1.0.0' spec_genome_v3 = sc.read_visium(visium_pth, genome='GRCh38') nospec_genome_v3 = sc.read_visium(visium_pth) assert_anndata_equal(spec_genome_v3, nospec_genome_v3)
13,207
def send_spam_user_email(recipient, deposit=None, community=None): """Send email notification to blocked user after spam detection.""" msg = Message( _("Your Zenodo activity has been automatically marked as Spam."), sender=current_app.config.get('SUPPORT_EMAIL'), recipients=[recipient], ...
def send_spam_user_email(recipient, deposit=None, community=None): """Send email notification to blocked user after spam detection.""" msg = Message( _("Your Zenodo activity has been automatically marked as Spam."), sender=current_app.config.get('SUPPORT_EMAIL'), recipients=[recipient], ...