Best Python code snippet using slash
config.py
Source:config.py
...81 serializer = self.serializers[serializer_name]82 except KeyError:83 raise KeyError("Serializer {} doesn't exist or isn't registered".format(serializer_name))84 return serializer85 def _get_matchers(self, matcher_names):86 matchers = []87 try:88 for m in matcher_names:89 matchers.append(self.matchers[m])90 except KeyError:91 raise KeyError("Matcher {} doesn't exist or isn't registered".format(m))92 return matchers93 def use_cassette(self, path=None, **kwargs):94 if path is not None and not isinstance(path, six.string_types):95 function = path96 # Assume this is an attempt to decorate a function97 return self._use_cassette(**kwargs)(function)98 return self._use_cassette(path=path, **kwargs)99 def _use_cassette(self, with_current_defaults=False, **kwargs):100 if with_current_defaults:101 config = self.get_merged_config(**kwargs)102 return Cassette.use(**config)103 # This is made a function that evaluates every time a cassette104 # is made so that changes that are made to this VCR instance105 # that occur AFTER the `use_cassette` decorator is applied106 # still affect subsequent calls to the decorated function.107 args_getter = functools.partial(self.get_merged_config, **kwargs)108 return Cassette.use_arg_getter(args_getter)109 def get_merged_config(self, **kwargs):110 serializer_name = kwargs.get("serializer", self.serializer)111 matcher_names = kwargs.get("match_on", self.match_on)112 path_transformer = kwargs.get("path_transformer", self.path_transformer)113 func_path_generator = kwargs.get("func_path_generator", self.func_path_generator)114 cassette_library_dir = kwargs.get("cassette_library_dir", self.cassette_library_dir)115 additional_matchers = kwargs.get("additional_matchers", ())116 if cassette_library_dir:117 def add_cassette_library_dir(path):118 if not path.startswith(cassette_library_dir):119 return os.path.join(cassette_library_dir, path)120 return path121 path_transformer = compose(add_cassette_library_dir, path_transformer)122 elif not func_path_generator:123 # If we don't have a library dir, use the functions124 # location to build a full path for cassettes.125 func_path_generator = self._build_path_from_func_using_module126 merged_config = {127 "serializer": self._get_serializer(serializer_name),128 "persister": self.persister,129 "match_on": self._get_matchers(tuple(matcher_names) + tuple(additional_matchers)),130 "record_mode": kwargs.get("record_mode", self.record_mode),131 "before_record_request": self._build_before_record_request(kwargs),132 "before_record_response": self._build_before_record_response(kwargs),133 "custom_patches": self._custom_patches + kwargs.get("custom_patches", ()),134 "inject": kwargs.get("inject_cassette", self.inject_cassette),135 "path_transformer": path_transformer,136 "func_path_generator": func_path_generator,137 }138 path = kwargs.get("path")139 if path:140 merged_config["path"] = path141 return merged_config142 def _build_before_record_response(self, options):143 before_record_response = options.get("before_record_response", self.before_record_response)...
mysql.py
Source:mysql.py
...24 return con25Entity = Union[dict, Model, dataclasses.dataclass]26Matcher = Tuple[str, Any]27Matchers = Union[List[Matcher], Matcher]28def _get_matchers(matchers: Union[Matchers, int]) -> Tuple[List[Matcher], str]:29 if isinstance(matchers, int):30 matchers = [("id", matchers)]31 elif isinstance(matchers[0], str):32 matchers = [matchers]33 return matchers, " AND ".join([f"{key}='{value}'" for key, value in matchers])34class _Table:35 _table_name: str36 _cur: MySQLCursor37 def __init__(self, cur, table_name: str):38 self._cur = cur39 self._table_name = table_name40 def find_by(self, matchers: Union[Matchers, int]) -> MySQLCursor:41 matchers, where_clause = _get_matchers(matchers)42 self._cur.execute(f"SELECT * FROM `{self._table_name}` WHERE {where_clause}")43 return self._cur44 def insert(self, dc: dataclasses.dataclass, keys: Optional[List[str]] = None,45 exclude_keys: Optional[List[str]] = None, replace: bool = False) -> int:46 if replace and self.find_by(meta.get_pk(dc)).rowcount > 0: # TODO: better written as sql47 self.delete(meta.get_pk(dc))48 data = serialize(dc).for_sql_insert()49 if keys is None:50 keys = list(data.keys())51 elif isinstance(keys, dict):52 keys = list(keys.keys())53 if exclude_keys is not None:54 for ex in exclude_keys:55 keys.remove(ex)56 values = [data[key] if key in data else None for key in keys]57 placeholder = ", ".join(["%s"] * len(keys))58 table_name = self._table_name59 qry = "INSERT INTO {table_name} ({columns}) VALUES ({values})" \60 .format(table_name=table_name, columns=",".join(keys), values=placeholder)61 logging.debug(qry)62 self._cur.execute(qry, values)63 return self._cur.lastrowid64 def update(self, dc: dataclasses.dataclass, keys: Optional[List[str]] = None,65 matchers: Optional[Matchers] = None):66 def update_value(name: str) -> str:67 return '{name}=%s'.format(name=name)68 data: dict = serialize(dc).for_sql_update()69 if keys is None:70 keys = list(data.keys())71 if isinstance(keys, dict):72 keys = list(keys.keys())73 if matchers is None:74 matchers = [meta.get_pk(dc)]75 # del data[matchers[0][0]]76 matchers, where_clause = _get_matchers(matchers)77 table_name = self._table_name78 values = [data[key] for key in keys]79 update_values = map(update_value, keys)80 qry = "UPDATE {table_name} SET {update_values} WHERE {where_clause}" \81 .format(table_name=table_name, update_values=",".join(update_values), where_clause=where_clause)82 logging.debug(qry)83 return self._cur.execute(qry, values)84 def delete(self, matchers: Union[Matchers, int]):85 if isinstance(matchers, int):86 where_clause = f"id={matchers}"87 elif isinstance(matchers[0], list):88 where_clause = " AND ".join([f"{key}='{value}'" for [key, value] in matchers])89 else:90 key, value = matchers...
test_similarity.py
Source:test_similarity.py
...21 num_queries = 822 num_spec_peaks = 623 num_query_peaks = 4824 # Get spectra:25 for matcher_cls in _get_matchers():26 specs = _get_spectra(num_spectra, num_spec_peaks)27 queries = _get_spectra(num_queries, num_query_peaks)28 matcher = matcher_cls(specs)29 result = matcher.search(queries)30 self.assertEqual(result.shape, (num_queries, num_spectra))31 def test_search_equal(self):32 '''Test search method of SpectraMatcher class.'''33 for matcher_cls in _get_matchers():34 specs = np.array([[[1, 0.2], [10, 0.3]]])35 queries = np.copy(specs)36 matcher = matcher_cls(specs)37 result = matcher.search(queries)38 self.assertAlmostEqual(result[0][0], 0, 12)39 def test_search_distant(self):40 '''Test search method of SpectraMatcher class.'''41 for matcher_cls in _get_matchers():42 specs = np.array([[[800.0, 0.2]]])43 queries = np.array([[[1e-16, 1e-16], [8000.0, 0.2]]])44 matcher = matcher_cls(specs)45 result = matcher.search(queries)46 self.assertAlmostEqual(result[0][0], 1, 12)47 def test_search_real(self):48 '''Test search method of SpectraMatcher class.'''49 # Get spectra:50 filename = os.path.join(*[Path(__file__).parents[3],51 'data/'52 'MoNA-export-LC-MS-MS_Positive_Mode.json'])53 # Oxolinic acid, Flumequine false positive:54 df = mona.get_spectra(filename, 100).loc[[59, 51]]55 specs = get_spectra(df)56 scores = []57 for matcher_cls in _get_matchers():58 spec = specs[0].copy()59 query = specs[1].copy()60 matcher = matcher_cls([spec])61 result = matcher.search([query])62 scores.append(result[0][0])63 np.testing.assert_allclose(64 scores,65 [0.019920, 0.009988, 0.126344, 0.063200, 1.0, 1.0,66 0.092896, 0.763453, 0.063200],67 atol=0.01)68def _get_spectra(num_spectra, num_peaks):69 '''Get spectra, sorted by mass.'''70 spec = np.random.rand(num_spectra, num_peaks, 2)71 return np.sort(spec, axis=1)72def _get_matchers():73 '''Get matchers.'''74 return [partial(similarity.SimpleSpectraMatcher,75 mass_acc=float('inf'), scorer=np.max),76 partial(similarity.SimpleSpectraMatcher,77 mass_acc=float('inf'), scorer=np.average),78 partial(similarity.SimpleSpectraMatcher,79 mass_acc=0.1, scorer=np.max),80 partial(similarity.SimpleSpectraMatcher,81 mass_acc=0.1, scorer=np.average),82 partial(similarity.SimpleSpectraMatcher,83 mass_acc=0.01, scorer=np.max),84 partial(similarity.SimpleSpectraMatcher,85 mass_acc=0.01, scorer=np.average),86 similarity.BinnedSpectraMatcher,...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!