hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
1.02M
avg_line_length
float64
1
417k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
1 class
is_sharp_comment_removed
bool
1 class
f7275f87f8a46c54c59aa154abe1e2df4f3c1c6d
18,246
py
Python
tests/core/test_datamodules.py
lsqshr/pytorch-lightning
c6b68883879e38719688865aceac746477f0a9b9
[ "Apache-2.0" ]
null
null
null
tests/core/test_datamodules.py
lsqshr/pytorch-lightning
c6b68883879e38719688865aceac746477f0a9b9
[ "Apache-2.0" ]
null
null
null
tests/core/test_datamodules.py
lsqshr/pytorch-lightning
c6b68883879e38719688865aceac746477f0a9b9
[ "Apache-2.0" ]
null
null
null
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pickle from argparse import ArgumentParser from typing import Any, Dict from unittest import mock from unittest.mock import call, PropertyMock import pytest import torch from pytorch_lightning import LightningDataModule, Trainer from pytorch_lightning.callbacks import ModelCheckpoint from pytorch_lightning.utilities import AttributeDict from pytorch_lightning.utilities.model_helpers import is_overridden from tests.helpers import BoringDataModule, BoringModel from tests.helpers.datamodules import ClassifDataModule from tests.helpers.runif import RunIf from tests.helpers.simple_models import ClassificationModel from tests.helpers.utils import reset_seed @mock.patch("pytorch_lightning.trainer.trainer.Trainer.node_rank", new_callable=PropertyMock) @mock.patch("pytorch_lightning.trainer.trainer.Trainer.local_rank", new_callable=PropertyMock) def test_can_prepare_data(local_rank, node_rank): model = BoringModel() dm = BoringDataModule() trainer = Trainer() trainer.model = model trainer.datamodule = dm # 1 no DM # prepare_data_per_node = True # local rank = 0 (True) trainer.prepare_data_per_node = True dm.random_full = None dm._has_prepared_data = False local_rank.return_value = 0 assert trainer.local_rank == 0 assert trainer.data_connector.can_prepare_data() trainer.data_connector.prepare_data() assert dm.random_full is not None # local rank = 1 (False) dm.random_full = None dm._has_prepared_data = False local_rank.return_value = 1 assert trainer.local_rank == 1 assert not trainer.data_connector.can_prepare_data() trainer.data_connector.prepare_data() assert dm.random_full is None # prepare_data_per_node = False (prepare across all nodes) # global rank = 0 (True) dm.random_full = None dm._has_prepared_data = False trainer.prepare_data_per_node = False node_rank.return_value = 0 local_rank.return_value = 0 assert trainer.data_connector.can_prepare_data() trainer.data_connector.prepare_data() assert dm.random_full is not None # global rank = 1 (False) dm.random_full = None dm._has_prepared_data = False node_rank.return_value = 1 local_rank.return_value = 0 assert not trainer.data_connector.can_prepare_data() trainer.data_connector.prepare_data() assert dm.random_full is None node_rank.return_value = 0 local_rank.return_value = 1 assert not trainer.data_connector.can_prepare_data() trainer.data_connector.prepare_data() assert dm.random_full is None # 2 dm # prepar per node = True # local rank = 0 (True) trainer.prepare_data_per_node = True local_rank.return_value = 0 # is_overridden prepare data = True # has been called # False dm._has_prepared_data = True assert not trainer.data_connector.can_prepare_data() # has not been called # True dm._has_prepared_data = False assert trainer.data_connector.can_prepare_data() # is_overridden prepare data = False # True dm.prepare_data = None assert trainer.data_connector.can_prepare_data() def test_hooks_no_recursion_error(): # hooks were appended in cascade every tine a new data module was instantiated leading to a recursion error. # See https://github.com/PyTorchLightning/pytorch-lightning/issues/3652 class DummyDM(LightningDataModule): def setup(self, *args, **kwargs): pass def prepare_data(self, *args, **kwargs): pass for i in range(1005): dm = DummyDM() dm.setup() dm.prepare_data() def test_helper_boringdatamodule(): dm = BoringDataModule() dm.prepare_data() dm.setup() def test_helper_boringdatamodule_with_verbose_setup(): dm = BoringDataModule() dm.prepare_data() dm.setup("fit") dm.setup("test") def test_data_hooks_called(): dm = BoringDataModule() assert not dm.has_prepared_data assert not dm.has_setup_fit assert not dm.has_setup_test assert not dm.has_setup_validate assert not dm.has_setup_predict assert not dm.has_teardown_fit assert not dm.has_teardown_test assert not dm.has_teardown_validate assert not dm.has_teardown_predict dm.prepare_data() assert dm.has_prepared_data assert not dm.has_setup_fit assert not dm.has_setup_test assert not dm.has_setup_validate assert not dm.has_setup_predict assert not dm.has_teardown_fit assert not dm.has_teardown_test assert not dm.has_teardown_validate assert not dm.has_teardown_predict dm.setup() assert dm.has_prepared_data assert dm.has_setup_fit assert dm.has_setup_test assert dm.has_setup_validate assert not dm.has_setup_predict assert not dm.has_teardown_fit assert not dm.has_teardown_test assert not dm.has_teardown_validate assert not dm.has_teardown_predict dm.teardown() assert dm.has_prepared_data assert dm.has_setup_fit assert dm.has_setup_test assert dm.has_setup_validate assert not dm.has_setup_predict assert dm.has_teardown_fit assert dm.has_teardown_test assert dm.has_teardown_validate assert not dm.has_teardown_predict @pytest.mark.parametrize("use_kwarg", (False, True)) def test_data_hooks_called_verbose(use_kwarg): dm = BoringDataModule() dm.prepare_data() assert not dm.has_setup_fit assert not dm.has_setup_test assert not dm.has_setup_validate assert not dm.has_setup_predict assert not dm.has_teardown_fit assert not dm.has_teardown_test assert not dm.has_teardown_validate assert not dm.has_teardown_predict dm.setup(stage="fit") if use_kwarg else dm.setup("fit") assert dm.has_setup_fit assert not dm.has_setup_validate assert not dm.has_setup_test assert not dm.has_setup_predict dm.setup(stage="validate") if use_kwarg else dm.setup("validate") assert dm.has_setup_fit assert dm.has_setup_validate assert not dm.has_setup_test assert not dm.has_setup_predict dm.setup(stage="test") if use_kwarg else dm.setup("test") assert dm.has_setup_fit assert dm.has_setup_validate assert dm.has_setup_test assert not dm.has_setup_predict dm.setup(stage="predict") if use_kwarg else dm.setup("predict") assert dm.has_setup_fit assert dm.has_setup_validate assert dm.has_setup_test assert dm.has_setup_predict dm.teardown(stage="fit") if use_kwarg else dm.teardown("fit") assert dm.has_teardown_fit assert not dm.has_teardown_validate assert not dm.has_teardown_test assert not dm.has_teardown_predict dm.teardown(stage="validate") if use_kwarg else dm.teardown("validate") assert dm.has_teardown_fit assert dm.has_teardown_validate assert not dm.has_teardown_test assert not dm.has_teardown_predict dm.teardown(stage="test") if use_kwarg else dm.teardown("test") assert dm.has_teardown_fit assert dm.has_teardown_validate assert dm.has_teardown_test assert not dm.has_teardown_predict dm.teardown(stage="predict") if use_kwarg else dm.teardown("predict") assert dm.has_teardown_fit assert dm.has_teardown_validate assert dm.has_teardown_test assert dm.has_teardown_predict def test_dm_add_argparse_args(tmpdir): parser = ArgumentParser() parser = BoringDataModule.add_argparse_args(parser) args = parser.parse_args(["--data_dir", str(tmpdir)]) assert args.data_dir == str(tmpdir) def test_dm_init_from_argparse_args(tmpdir): parser = ArgumentParser() parser = BoringDataModule.add_argparse_args(parser) args = parser.parse_args(["--data_dir", str(tmpdir)]) dm = BoringDataModule.from_argparse_args(args) dm.prepare_data() dm.setup() assert dm.data_dir == args.data_dir == str(tmpdir) def test_dm_pickle_after_init(): dm = BoringDataModule() pickle.dumps(dm) def test_train_loop_only(tmpdir): reset_seed() dm = ClassifDataModule() model = ClassificationModel() model.validation_step = None model.validation_step_end = None model.validation_epoch_end = None model.test_step = None model.test_step_end = None model.test_epoch_end = None trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, weights_summary=None) # fit model trainer.fit(model, datamodule=dm) assert trainer.state.finished, f"Training failed with {trainer.state}" assert trainer.callback_metrics["train_loss"] < 1.0 def test_train_val_loop_only(tmpdir): reset_seed() dm = ClassifDataModule() model = ClassificationModel() model.validation_step = None model.validation_step_end = None model.validation_epoch_end = None trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, weights_summary=None) # fit model trainer.fit(model, datamodule=dm) assert trainer.state.finished, f"Training failed with {trainer.state}" assert trainer.callback_metrics["train_loss"] < 1.0 def test_dm_checkpoint_save(tmpdir): class CustomBoringModel(BoringModel): def validation_step(self, batch, batch_idx): out = super().validation_step(batch, batch_idx) self.log("early_stop_on", out["x"]) return out class CustomBoringDataModule(BoringDataModule): def on_save_checkpoint(self, checkpoint: Dict[str, Any]) -> None: checkpoint[self.__class__.__name__] = self.__class__.__name__ def on_load_checkpoint(self, checkpoint: Dict[str, Any]) -> None: self.checkpoint_state = checkpoint.get(self.__class__.__name__) reset_seed() dm = CustomBoringDataModule() model = CustomBoringModel() trainer = Trainer( default_root_dir=tmpdir, max_epochs=1, limit_train_batches=2, limit_val_batches=1, weights_summary=None, callbacks=[ModelCheckpoint(dirpath=tmpdir, monitor="early_stop_on")], ) # fit model trainer.fit(model, dm) assert trainer.state.finished, f"Training failed with {trainer.state}" checkpoint_path = list(trainer.checkpoint_callback.best_k_models.keys())[0] checkpoint = torch.load(checkpoint_path) assert dm.__class__.__name__ in checkpoint assert checkpoint[dm.__class__.__name__] == dm.__class__.__name__ def test_full_loop(tmpdir): reset_seed() dm = ClassifDataModule() model = ClassificationModel() trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, weights_summary=None, deterministic=True) # fit model trainer.fit(model, dm) assert trainer.state.finished, f"Training failed with {trainer.state}" assert dm.trainer is not None # validate result = trainer.validate(model, dm) assert dm.trainer is not None assert result[0]["val_acc"] > 0.7 # test result = trainer.test(model, dm) assert dm.trainer is not None assert result[0]["test_acc"] > 0.6 @RunIf(min_gpus=1) @mock.patch("pytorch_lightning.accelerators.accelerator.Accelerator.lightning_module", new_callable=PropertyMock) def test_dm_apply_batch_transfer_handler(get_module_mock): expected_device = torch.device("cuda", 0) class CustomBatch: def __init__(self, data): self.samples = data[0] self.targets = data[1] class CurrentTestDM(LightningDataModule): rank = 0 transfer_batch_to_device_hook_rank = None on_before_batch_transfer_hook_rank = None on_after_batch_transfer_hook_rank = None def on_before_batch_transfer(self, batch, dataloader_idx): assert dataloader_idx == 0 self.on_before_batch_transfer_hook_rank = self.rank self.rank += 1 batch.samples += 1 return batch def on_after_batch_transfer(self, batch, dataloader_idx): assert dataloader_idx == 0 assert batch.samples.device == batch.targets.device == expected_device self.on_after_batch_transfer_hook_rank = self.rank self.rank += 1 batch.targets *= 2 return batch def transfer_batch_to_device(self, batch, device, dataloader_idx): assert dataloader_idx == 0 self.transfer_batch_to_device_hook_rank = self.rank self.rank += 1 batch.samples = batch.samples.to(device) batch.targets = batch.targets.to(device) return batch dm = CurrentTestDM() model = BoringModel() batch = CustomBatch((torch.zeros(5, 32), torch.ones(5, 1, dtype=torch.long))) trainer = Trainer(gpus=1) # running .fit() would require us to implement custom data loaders, we mock the model reference instead get_module_mock.return_value = model if is_overridden("transfer_batch_to_device", dm): model.transfer_batch_to_device = dm.transfer_batch_to_device model.on_before_batch_transfer = dm.on_before_batch_transfer model.transfer_batch_to_device = dm.transfer_batch_to_device model.on_after_batch_transfer = dm.on_after_batch_transfer batch_gpu = trainer.accelerator.batch_to_device(batch, expected_device) assert dm.on_before_batch_transfer_hook_rank == 0 assert dm.transfer_batch_to_device_hook_rank == 1 assert dm.on_after_batch_transfer_hook_rank == 2 assert batch_gpu.samples.device == batch_gpu.targets.device == expected_device assert torch.allclose(batch_gpu.samples.cpu(), torch.ones(5, 32)) assert torch.allclose(batch_gpu.targets.cpu(), torch.ones(5, 1, dtype=torch.long) * 2) def test_dm_reload_dataloaders_every_n_epochs(tmpdir): """ Test datamodule, where trainer argument reload_dataloaders_every_n_epochs is set to a non negative integer """ class CustomBoringDataModule(BoringDataModule): def __init__(self): super().__init__() self._epochs_called_for = [] def train_dataloader(self): assert self.trainer.current_epoch not in self._epochs_called_for self._epochs_called_for.append(self.trainer.current_epoch) return super().train_dataloader() dm = CustomBoringDataModule() model = BoringModel() model.validation_step = None model.validation_step_end = None model.validation_epoch_end = None model.test_step = None model.test_step_end = None model.test_epoch_end = None trainer = Trainer(default_root_dir=tmpdir, max_epochs=3, limit_train_batches=2, reload_dataloaders_every_n_epochs=2) trainer.fit(model, dm) class DummyDS(torch.utils.data.Dataset): def __getitem__(self, index): return 1 def __len__(self): return 100 class DummyIDS(torch.utils.data.IterableDataset): def __iter__(self): yield 1 @pytest.mark.parametrize("iterable", (False, True)) def test_dm_init_from_datasets_dataloaders(iterable): ds = DummyIDS if iterable else DummyDS train_ds = ds() dm = LightningDataModule.from_datasets(train_ds, batch_size=4, num_workers=0) with mock.patch("pytorch_lightning.core.datamodule.DataLoader") as dl_mock: dm.train_dataloader() dl_mock.assert_called_once_with(train_ds, batch_size=4, shuffle=not iterable, num_workers=0, pin_memory=True) assert dm.val_dataloader() is None assert dm.test_dataloader() is None train_ds_sequence = [ds(), ds()] dm = LightningDataModule.from_datasets(train_ds_sequence, batch_size=4, num_workers=0) with mock.patch("pytorch_lightning.core.datamodule.DataLoader") as dl_mock: dm.train_dataloader() dl_mock.assert_has_calls( [ call(train_ds_sequence[0], batch_size=4, shuffle=not iterable, num_workers=0, pin_memory=True), call(train_ds_sequence[1], batch_size=4, shuffle=not iterable, num_workers=0, pin_memory=True), ] ) assert dm.val_dataloader() is None assert dm.test_dataloader() is None valid_ds = ds() test_ds = ds() dm = LightningDataModule.from_datasets(val_dataset=valid_ds, test_dataset=test_ds, batch_size=2, num_workers=0) with mock.patch("pytorch_lightning.core.datamodule.DataLoader") as dl_mock: dm.val_dataloader() dl_mock.assert_called_with(valid_ds, batch_size=2, shuffle=False, num_workers=0, pin_memory=True) dm.test_dataloader() dl_mock.assert_called_with(test_ds, batch_size=2, shuffle=False, num_workers=0, pin_memory=True) assert dm.train_dataloader() is None valid_dss = [ds(), ds()] test_dss = [ds(), ds()] dm = LightningDataModule.from_datasets(train_ds, valid_dss, test_dss, batch_size=4, num_workers=0) with mock.patch("pytorch_lightning.core.datamodule.DataLoader") as dl_mock: dm.val_dataloader() dm.test_dataloader() dl_mock.assert_has_calls( [ call(valid_dss[0], batch_size=4, shuffle=False, num_workers=0, pin_memory=True), call(valid_dss[1], batch_size=4, shuffle=False, num_workers=0, pin_memory=True), call(test_dss[0], batch_size=4, shuffle=False, num_workers=0, pin_memory=True), call(test_dss[1], batch_size=4, shuffle=False, num_workers=0, pin_memory=True), ] ) class DataModuleWithHparams(LightningDataModule): def __init__(self, arg0, arg1, kwarg0=None): super().__init__() self.save_hyperparameters() def test_simple_hyperparameters_saving(): data = DataModuleWithHparams(10, "foo", kwarg0="bar") assert data.hparams == AttributeDict({"arg0": 10, "arg1": "foo", "kwarg0": "bar"})
33.478899
120
0.71961
import pickle from argparse import ArgumentParser from typing import Any, Dict from unittest import mock from unittest.mock import call, PropertyMock import pytest import torch from pytorch_lightning import LightningDataModule, Trainer from pytorch_lightning.callbacks import ModelCheckpoint from pytorch_lightning.utilities import AttributeDict from pytorch_lightning.utilities.model_helpers import is_overridden from tests.helpers import BoringDataModule, BoringModel from tests.helpers.datamodules import ClassifDataModule from tests.helpers.runif import RunIf from tests.helpers.simple_models import ClassificationModel from tests.helpers.utils import reset_seed @mock.patch("pytorch_lightning.trainer.trainer.Trainer.node_rank", new_callable=PropertyMock) @mock.patch("pytorch_lightning.trainer.trainer.Trainer.local_rank", new_callable=PropertyMock) def test_can_prepare_data(local_rank, node_rank): model = BoringModel() dm = BoringDataModule() trainer = Trainer() trainer.model = model trainer.datamodule = dm trainer.prepare_data_per_node = True dm.random_full = None dm._has_prepared_data = False local_rank.return_value = 0 assert trainer.local_rank == 0 assert trainer.data_connector.can_prepare_data() trainer.data_connector.prepare_data() assert dm.random_full is not None dm.random_full = None dm._has_prepared_data = False local_rank.return_value = 1 assert trainer.local_rank == 1 assert not trainer.data_connector.can_prepare_data() trainer.data_connector.prepare_data() assert dm.random_full is None dm.random_full = None dm._has_prepared_data = False trainer.prepare_data_per_node = False node_rank.return_value = 0 local_rank.return_value = 0 assert trainer.data_connector.can_prepare_data() trainer.data_connector.prepare_data() assert dm.random_full is not None dm.random_full = None dm._has_prepared_data = False node_rank.return_value = 1 local_rank.return_value = 0 assert not trainer.data_connector.can_prepare_data() trainer.data_connector.prepare_data() assert dm.random_full is None node_rank.return_value = 0 local_rank.return_value = 1 assert not trainer.data_connector.can_prepare_data() trainer.data_connector.prepare_data() assert dm.random_full is None trainer.prepare_data_per_node = True local_rank.return_value = 0 dm._has_prepared_data = True assert not trainer.data_connector.can_prepare_data() dm._has_prepared_data = False assert trainer.data_connector.can_prepare_data() dm.prepare_data = None assert trainer.data_connector.can_prepare_data() def test_hooks_no_recursion_error(): class DummyDM(LightningDataModule): def setup(self, *args, **kwargs): pass def prepare_data(self, *args, **kwargs): pass for i in range(1005): dm = DummyDM() dm.setup() dm.prepare_data() def test_helper_boringdatamodule(): dm = BoringDataModule() dm.prepare_data() dm.setup() def test_helper_boringdatamodule_with_verbose_setup(): dm = BoringDataModule() dm.prepare_data() dm.setup("fit") dm.setup("test") def test_data_hooks_called(): dm = BoringDataModule() assert not dm.has_prepared_data assert not dm.has_setup_fit assert not dm.has_setup_test assert not dm.has_setup_validate assert not dm.has_setup_predict assert not dm.has_teardown_fit assert not dm.has_teardown_test assert not dm.has_teardown_validate assert not dm.has_teardown_predict dm.prepare_data() assert dm.has_prepared_data assert not dm.has_setup_fit assert not dm.has_setup_test assert not dm.has_setup_validate assert not dm.has_setup_predict assert not dm.has_teardown_fit assert not dm.has_teardown_test assert not dm.has_teardown_validate assert not dm.has_teardown_predict dm.setup() assert dm.has_prepared_data assert dm.has_setup_fit assert dm.has_setup_test assert dm.has_setup_validate assert not dm.has_setup_predict assert not dm.has_teardown_fit assert not dm.has_teardown_test assert not dm.has_teardown_validate assert not dm.has_teardown_predict dm.teardown() assert dm.has_prepared_data assert dm.has_setup_fit assert dm.has_setup_test assert dm.has_setup_validate assert not dm.has_setup_predict assert dm.has_teardown_fit assert dm.has_teardown_test assert dm.has_teardown_validate assert not dm.has_teardown_predict @pytest.mark.parametrize("use_kwarg", (False, True)) def test_data_hooks_called_verbose(use_kwarg): dm = BoringDataModule() dm.prepare_data() assert not dm.has_setup_fit assert not dm.has_setup_test assert not dm.has_setup_validate assert not dm.has_setup_predict assert not dm.has_teardown_fit assert not dm.has_teardown_test assert not dm.has_teardown_validate assert not dm.has_teardown_predict dm.setup(stage="fit") if use_kwarg else dm.setup("fit") assert dm.has_setup_fit assert not dm.has_setup_validate assert not dm.has_setup_test assert not dm.has_setup_predict dm.setup(stage="validate") if use_kwarg else dm.setup("validate") assert dm.has_setup_fit assert dm.has_setup_validate assert not dm.has_setup_test assert not dm.has_setup_predict dm.setup(stage="test") if use_kwarg else dm.setup("test") assert dm.has_setup_fit assert dm.has_setup_validate assert dm.has_setup_test assert not dm.has_setup_predict dm.setup(stage="predict") if use_kwarg else dm.setup("predict") assert dm.has_setup_fit assert dm.has_setup_validate assert dm.has_setup_test assert dm.has_setup_predict dm.teardown(stage="fit") if use_kwarg else dm.teardown("fit") assert dm.has_teardown_fit assert not dm.has_teardown_validate assert not dm.has_teardown_test assert not dm.has_teardown_predict dm.teardown(stage="validate") if use_kwarg else dm.teardown("validate") assert dm.has_teardown_fit assert dm.has_teardown_validate assert not dm.has_teardown_test assert not dm.has_teardown_predict dm.teardown(stage="test") if use_kwarg else dm.teardown("test") assert dm.has_teardown_fit assert dm.has_teardown_validate assert dm.has_teardown_test assert not dm.has_teardown_predict dm.teardown(stage="predict") if use_kwarg else dm.teardown("predict") assert dm.has_teardown_fit assert dm.has_teardown_validate assert dm.has_teardown_test assert dm.has_teardown_predict def test_dm_add_argparse_args(tmpdir): parser = ArgumentParser() parser = BoringDataModule.add_argparse_args(parser) args = parser.parse_args(["--data_dir", str(tmpdir)]) assert args.data_dir == str(tmpdir) def test_dm_init_from_argparse_args(tmpdir): parser = ArgumentParser() parser = BoringDataModule.add_argparse_args(parser) args = parser.parse_args(["--data_dir", str(tmpdir)]) dm = BoringDataModule.from_argparse_args(args) dm.prepare_data() dm.setup() assert dm.data_dir == args.data_dir == str(tmpdir) def test_dm_pickle_after_init(): dm = BoringDataModule() pickle.dumps(dm) def test_train_loop_only(tmpdir): reset_seed() dm = ClassifDataModule() model = ClassificationModel() model.validation_step = None model.validation_step_end = None model.validation_epoch_end = None model.test_step = None model.test_step_end = None model.test_epoch_end = None trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, weights_summary=None) trainer.fit(model, datamodule=dm) assert trainer.state.finished, f"Training failed with {trainer.state}" assert trainer.callback_metrics["train_loss"] < 1.0 def test_train_val_loop_only(tmpdir): reset_seed() dm = ClassifDataModule() model = ClassificationModel() model.validation_step = None model.validation_step_end = None model.validation_epoch_end = None trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, weights_summary=None) trainer.fit(model, datamodule=dm) assert trainer.state.finished, f"Training failed with {trainer.state}" assert trainer.callback_metrics["train_loss"] < 1.0 def test_dm_checkpoint_save(tmpdir): class CustomBoringModel(BoringModel): def validation_step(self, batch, batch_idx): out = super().validation_step(batch, batch_idx) self.log("early_stop_on", out["x"]) return out class CustomBoringDataModule(BoringDataModule): def on_save_checkpoint(self, checkpoint: Dict[str, Any]) -> None: checkpoint[self.__class__.__name__] = self.__class__.__name__ def on_load_checkpoint(self, checkpoint: Dict[str, Any]) -> None: self.checkpoint_state = checkpoint.get(self.__class__.__name__) reset_seed() dm = CustomBoringDataModule() model = CustomBoringModel() trainer = Trainer( default_root_dir=tmpdir, max_epochs=1, limit_train_batches=2, limit_val_batches=1, weights_summary=None, callbacks=[ModelCheckpoint(dirpath=tmpdir, monitor="early_stop_on")], ) trainer.fit(model, dm) assert trainer.state.finished, f"Training failed with {trainer.state}" checkpoint_path = list(trainer.checkpoint_callback.best_k_models.keys())[0] checkpoint = torch.load(checkpoint_path) assert dm.__class__.__name__ in checkpoint assert checkpoint[dm.__class__.__name__] == dm.__class__.__name__ def test_full_loop(tmpdir): reset_seed() dm = ClassifDataModule() model = ClassificationModel() trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, weights_summary=None, deterministic=True) trainer.fit(model, dm) assert trainer.state.finished, f"Training failed with {trainer.state}" assert dm.trainer is not None result = trainer.validate(model, dm) assert dm.trainer is not None assert result[0]["val_acc"] > 0.7 result = trainer.test(model, dm) assert dm.trainer is not None assert result[0]["test_acc"] > 0.6 @RunIf(min_gpus=1) @mock.patch("pytorch_lightning.accelerators.accelerator.Accelerator.lightning_module", new_callable=PropertyMock) def test_dm_apply_batch_transfer_handler(get_module_mock): expected_device = torch.device("cuda", 0) class CustomBatch: def __init__(self, data): self.samples = data[0] self.targets = data[1] class CurrentTestDM(LightningDataModule): rank = 0 transfer_batch_to_device_hook_rank = None on_before_batch_transfer_hook_rank = None on_after_batch_transfer_hook_rank = None def on_before_batch_transfer(self, batch, dataloader_idx): assert dataloader_idx == 0 self.on_before_batch_transfer_hook_rank = self.rank self.rank += 1 batch.samples += 1 return batch def on_after_batch_transfer(self, batch, dataloader_idx): assert dataloader_idx == 0 assert batch.samples.device == batch.targets.device == expected_device self.on_after_batch_transfer_hook_rank = self.rank self.rank += 1 batch.targets *= 2 return batch def transfer_batch_to_device(self, batch, device, dataloader_idx): assert dataloader_idx == 0 self.transfer_batch_to_device_hook_rank = self.rank self.rank += 1 batch.samples = batch.samples.to(device) batch.targets = batch.targets.to(device) return batch dm = CurrentTestDM() model = BoringModel() batch = CustomBatch((torch.zeros(5, 32), torch.ones(5, 1, dtype=torch.long))) trainer = Trainer(gpus=1) get_module_mock.return_value = model if is_overridden("transfer_batch_to_device", dm): model.transfer_batch_to_device = dm.transfer_batch_to_device model.on_before_batch_transfer = dm.on_before_batch_transfer model.transfer_batch_to_device = dm.transfer_batch_to_device model.on_after_batch_transfer = dm.on_after_batch_transfer batch_gpu = trainer.accelerator.batch_to_device(batch, expected_device) assert dm.on_before_batch_transfer_hook_rank == 0 assert dm.transfer_batch_to_device_hook_rank == 1 assert dm.on_after_batch_transfer_hook_rank == 2 assert batch_gpu.samples.device == batch_gpu.targets.device == expected_device assert torch.allclose(batch_gpu.samples.cpu(), torch.ones(5, 32)) assert torch.allclose(batch_gpu.targets.cpu(), torch.ones(5, 1, dtype=torch.long) * 2) def test_dm_reload_dataloaders_every_n_epochs(tmpdir): class CustomBoringDataModule(BoringDataModule): def __init__(self): super().__init__() self._epochs_called_for = [] def train_dataloader(self): assert self.trainer.current_epoch not in self._epochs_called_for self._epochs_called_for.append(self.trainer.current_epoch) return super().train_dataloader() dm = CustomBoringDataModule() model = BoringModel() model.validation_step = None model.validation_step_end = None model.validation_epoch_end = None model.test_step = None model.test_step_end = None model.test_epoch_end = None trainer = Trainer(default_root_dir=tmpdir, max_epochs=3, limit_train_batches=2, reload_dataloaders_every_n_epochs=2) trainer.fit(model, dm) class DummyDS(torch.utils.data.Dataset): def __getitem__(self, index): return 1 def __len__(self): return 100 class DummyIDS(torch.utils.data.IterableDataset): def __iter__(self): yield 1 @pytest.mark.parametrize("iterable", (False, True)) def test_dm_init_from_datasets_dataloaders(iterable): ds = DummyIDS if iterable else DummyDS train_ds = ds() dm = LightningDataModule.from_datasets(train_ds, batch_size=4, num_workers=0) with mock.patch("pytorch_lightning.core.datamodule.DataLoader") as dl_mock: dm.train_dataloader() dl_mock.assert_called_once_with(train_ds, batch_size=4, shuffle=not iterable, num_workers=0, pin_memory=True) assert dm.val_dataloader() is None assert dm.test_dataloader() is None train_ds_sequence = [ds(), ds()] dm = LightningDataModule.from_datasets(train_ds_sequence, batch_size=4, num_workers=0) with mock.patch("pytorch_lightning.core.datamodule.DataLoader") as dl_mock: dm.train_dataloader() dl_mock.assert_has_calls( [ call(train_ds_sequence[0], batch_size=4, shuffle=not iterable, num_workers=0, pin_memory=True), call(train_ds_sequence[1], batch_size=4, shuffle=not iterable, num_workers=0, pin_memory=True), ] ) assert dm.val_dataloader() is None assert dm.test_dataloader() is None valid_ds = ds() test_ds = ds() dm = LightningDataModule.from_datasets(val_dataset=valid_ds, test_dataset=test_ds, batch_size=2, num_workers=0) with mock.patch("pytorch_lightning.core.datamodule.DataLoader") as dl_mock: dm.val_dataloader() dl_mock.assert_called_with(valid_ds, batch_size=2, shuffle=False, num_workers=0, pin_memory=True) dm.test_dataloader() dl_mock.assert_called_with(test_ds, batch_size=2, shuffle=False, num_workers=0, pin_memory=True) assert dm.train_dataloader() is None valid_dss = [ds(), ds()] test_dss = [ds(), ds()] dm = LightningDataModule.from_datasets(train_ds, valid_dss, test_dss, batch_size=4, num_workers=0) with mock.patch("pytorch_lightning.core.datamodule.DataLoader") as dl_mock: dm.val_dataloader() dm.test_dataloader() dl_mock.assert_has_calls( [ call(valid_dss[0], batch_size=4, shuffle=False, num_workers=0, pin_memory=True), call(valid_dss[1], batch_size=4, shuffle=False, num_workers=0, pin_memory=True), call(test_dss[0], batch_size=4, shuffle=False, num_workers=0, pin_memory=True), call(test_dss[1], batch_size=4, shuffle=False, num_workers=0, pin_memory=True), ] ) class DataModuleWithHparams(LightningDataModule): def __init__(self, arg0, arg1, kwarg0=None): super().__init__() self.save_hyperparameters() def test_simple_hyperparameters_saving(): data = DataModuleWithHparams(10, "foo", kwarg0="bar") assert data.hparams == AttributeDict({"arg0": 10, "arg1": "foo", "kwarg0": "bar"})
true
true
f7275fe5fae95e29aeb9f0a69b69a28a48dc9e9a
2,048
py
Python
jupyter_resource_usage/tests/test_basic.py
fcollonval/jupyter-resource-usage
77ef2341efdee67a1457b6c6a0de5e001ca4c3aa
[ "BSD-2-Clause" ]
1
2021-03-20T09:24:46.000Z
2021-03-20T09:24:46.000Z
jupyter_resource_usage/tests/test_basic.py
fcollonval/jupyter-resource-usage
77ef2341efdee67a1457b6c6a0de5e001ca4c3aa
[ "BSD-2-Clause" ]
null
null
null
jupyter_resource_usage/tests/test_basic.py
fcollonval/jupyter-resource-usage
77ef2341efdee67a1457b6c6a0de5e001ca4c3aa
[ "BSD-2-Clause" ]
null
null
null
from mock import MagicMock from mock import patch class TestBasic: """Some basic tests, checking import, making sure APIs remain consistent, etc""" def test_import_serverextension(self): """Check that serverextension hooks are available""" from jupyter_resource_usage import ( _jupyter_server_extension_paths, _jupyter_nbextension_paths, load_jupyter_server_extension, ) assert _jupyter_server_extension_paths() == [ {"module": "jupyter_resource_usage"} ] assert _jupyter_nbextension_paths() == [ { "section": "notebook", "dest": "jupyter_resource_usage", "src": "static", "require": "jupyter_resource_usage/main", } ] # mock a notebook app nbapp_mock = MagicMock() nbapp_mock.web_app.settings = {"base_url": ""} # mock these out for unit test with patch("tornado.ioloop.PeriodicCallback") as periodic_callback_mock, patch( "jupyter_resource_usage.ResourceUseDisplay" ) as resource_use_display_mock, patch( "jupyter_resource_usage.PrometheusHandler" ) as prometheus_handler_mock, patch( "jupyter_resource_usage.PSUtilMetricsLoader" ) as psutil_metrics_loader: # load up with mock load_jupyter_server_extension(nbapp_mock) # assert that we installed the application in settings print(nbapp_mock.web_app.settings) assert ( "jupyter_resource_usage_display_config" in nbapp_mock.web_app.settings ) # assert that we instantiated a periodic callback with the fake # prometheus assert periodic_callback_mock.return_value.start.call_count == 1 assert prometheus_handler_mock.call_count == 1 prometheus_handler_mock.assert_called_with( psutil_metrics_loader(nbapp_mock) )
35.929825
87
0.625488
from mock import MagicMock from mock import patch class TestBasic: def test_import_serverextension(self): from jupyter_resource_usage import ( _jupyter_server_extension_paths, _jupyter_nbextension_paths, load_jupyter_server_extension, ) assert _jupyter_server_extension_paths() == [ {"module": "jupyter_resource_usage"} ] assert _jupyter_nbextension_paths() == [ { "section": "notebook", "dest": "jupyter_resource_usage", "src": "static", "require": "jupyter_resource_usage/main", } ] nbapp_mock = MagicMock() nbapp_mock.web_app.settings = {"base_url": ""} with patch("tornado.ioloop.PeriodicCallback") as periodic_callback_mock, patch( "jupyter_resource_usage.ResourceUseDisplay" ) as resource_use_display_mock, patch( "jupyter_resource_usage.PrometheusHandler" ) as prometheus_handler_mock, patch( "jupyter_resource_usage.PSUtilMetricsLoader" ) as psutil_metrics_loader: load_jupyter_server_extension(nbapp_mock) print(nbapp_mock.web_app.settings) assert ( "jupyter_resource_usage_display_config" in nbapp_mock.web_app.settings ) assert periodic_callback_mock.return_value.start.call_count == 1 assert prometheus_handler_mock.call_count == 1 prometheus_handler_mock.assert_called_with( psutil_metrics_loader(nbapp_mock) )
true
true
f7275ff361eebaef39028e0b71a649811bfb8cc5
1,646
py
Python
multitrackpy/mtt.py
bbo-lab/multitrackpy
a25ebdb94969b0682c851ab69ba5895173b581d0
[ "BSD-3-Clause" ]
null
null
null
multitrackpy/mtt.py
bbo-lab/multitrackpy
a25ebdb94969b0682c851ab69ba5895173b581d0
[ "BSD-3-Clause" ]
null
null
null
multitrackpy/mtt.py
bbo-lab/multitrackpy
a25ebdb94969b0682c851ab69ba5895173b581d0
[ "BSD-3-Clause" ]
null
null
null
import numpy as np import h5py from pprint import pprint def read_calib(mtt_path): mtt_file = h5py.File(mtt_path) istracking = np.squeeze(np.asarray([mtt_file['mt']['cam_istracking']]) == 1) calind = np.squeeze(np.int32(mtt_file['mt']['calind']))[istracking] - 1 mc = { 'Rglobal': np.asarray(mtt_file['mt']['mc']['Rglobal']).transpose((0, 2, 1)), # in reverse order in h5 file! 'Tglobal': np.asarray(mtt_file['mt']['mc']['Tglobal']), 'cal': [] } for ci in calind: mc['cal'].append({ 'scaling': np.asarray(mtt_file[mtt_file['mt']['mc']['cal']['scaling'][ci, 0]]).T[0], 'icent': np.asarray(mtt_file[mtt_file['mt']['mc']['cal']['icent'][ci, 0]]).T[0], 'distortion_coefs': np.asarray(mtt_file[mtt_file['mt']['mc']['cal']['distortion_coefs'][ci, 0]]), 'sensorsize': np.asarray(mtt_file[mtt_file['mt']['mc']['cal']['sensorsize'][ci, 0]]).T[0], 'scale_pixels': np.asarray(mtt_file[mtt_file['mt']['mc']['cal']['scale_pixels'][ci, 0]]), }) # pprint(mc) return mc def read_video_paths(vid_dir, mtt_path): mtt_file = h5py.File(mtt_path) istracking = np.squeeze(np.asarray([mtt_file['mt']['cam_istracking']]) == 1) return [vid_dir + ''.join([chr(c) for c in mtt_file[mtt_file['mt']['vidname'][0, i]][:].T.astype(np.int)[0]]) for i in np.where(istracking)[0]] def read_spacecoords(mtt_path): mtt_file = h5py.File(mtt_path) return np.asarray(mtt_file['mt']['objmodel']['space_coord']) def read_frame_n(mtt_path): mtt_file = h5py.File(mtt_path) return len(mtt_file['mt']['t'])
36.577778
119
0.600243
import numpy as np import h5py from pprint import pprint def read_calib(mtt_path): mtt_file = h5py.File(mtt_path) istracking = np.squeeze(np.asarray([mtt_file['mt']['cam_istracking']]) == 1) calind = np.squeeze(np.int32(mtt_file['mt']['calind']))[istracking] - 1 mc = { 'Rglobal': np.asarray(mtt_file['mt']['mc']['Rglobal']).transpose((0, 2, 1)), 'Tglobal': np.asarray(mtt_file['mt']['mc']['Tglobal']), 'cal': [] } for ci in calind: mc['cal'].append({ 'scaling': np.asarray(mtt_file[mtt_file['mt']['mc']['cal']['scaling'][ci, 0]]).T[0], 'icent': np.asarray(mtt_file[mtt_file['mt']['mc']['cal']['icent'][ci, 0]]).T[0], 'distortion_coefs': np.asarray(mtt_file[mtt_file['mt']['mc']['cal']['distortion_coefs'][ci, 0]]), 'sensorsize': np.asarray(mtt_file[mtt_file['mt']['mc']['cal']['sensorsize'][ci, 0]]).T[0], 'scale_pixels': np.asarray(mtt_file[mtt_file['mt']['mc']['cal']['scale_pixels'][ci, 0]]), }) return mc def read_video_paths(vid_dir, mtt_path): mtt_file = h5py.File(mtt_path) istracking = np.squeeze(np.asarray([mtt_file['mt']['cam_istracking']]) == 1) return [vid_dir + ''.join([chr(c) for c in mtt_file[mtt_file['mt']['vidname'][0, i]][:].T.astype(np.int)[0]]) for i in np.where(istracking)[0]] def read_spacecoords(mtt_path): mtt_file = h5py.File(mtt_path) return np.asarray(mtt_file['mt']['objmodel']['space_coord']) def read_frame_n(mtt_path): mtt_file = h5py.File(mtt_path) return len(mtt_file['mt']['t'])
true
true
f727605ce453fa3224aa6df44afa7128f0668b0c
2,544
py
Python
tao_action_recognition/data_generation/split_dataset.py
morrimeg/tao_toolkit_recipes
011f5426e2cec44af5b686d0c6225836460202f8
[ "MIT" ]
null
null
null
tao_action_recognition/data_generation/split_dataset.py
morrimeg/tao_toolkit_recipes
011f5426e2cec44af5b686d0c6225836460202f8
[ "MIT" ]
null
null
null
tao_action_recognition/data_generation/split_dataset.py
morrimeg/tao_toolkit_recipes
011f5426e2cec44af5b686d0c6225836460202f8
[ "MIT" ]
null
null
null
# Copyright (c) 2021 NVIDIA CORPORATION. All rights reserved. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os import shutil import sys root_path = sys.argv[1] split_files_path = sys.argv[2] target_train_path = sys.argv[3] target_test_path = sys.argv[4] if not os.path.exists(target_train_path): os.makedirs(target_train_path) if not os.path.exists(target_test_path): os.makedirs(target_test_path) train_cnt = 0 test_cnt = 0 for class_name in os.listdir(root_path): split_files = os.path.join(split_files_path, class_name + "_test_split1.txt") cls_train_path = os.path.join(target_train_path, class_name) cls_test_path = os.path.join(target_test_path, class_name) if not os.path.exists(cls_train_path): os.makedirs(cls_train_path) if not os.path.exists(cls_test_path): os.makedirs(cls_test_path) with open(split_files, "r") as f: split_list = f.readlines() for line in split_list: video_name, label = line.split() video_name = video_name.split(".")[0] cur_path = os.path.join(root_path, class_name, video_name) if int(label) == 1: train_cnt += 1 des_path = os.path.join(target_train_path, class_name, video_name) shutil.move(cur_path, des_path) elif int(label) == 2: test_cnt += 1 des_path = os.path.join(target_test_path, class_name, video_name) shutil.move(cur_path, des_path) print("Split 1: \n Train: {}\n Test: {}".format(train_cnt, test_cnt))
39.75
81
0.72445
import os import shutil import sys root_path = sys.argv[1] split_files_path = sys.argv[2] target_train_path = sys.argv[3] target_test_path = sys.argv[4] if not os.path.exists(target_train_path): os.makedirs(target_train_path) if not os.path.exists(target_test_path): os.makedirs(target_test_path) train_cnt = 0 test_cnt = 0 for class_name in os.listdir(root_path): split_files = os.path.join(split_files_path, class_name + "_test_split1.txt") cls_train_path = os.path.join(target_train_path, class_name) cls_test_path = os.path.join(target_test_path, class_name) if not os.path.exists(cls_train_path): os.makedirs(cls_train_path) if not os.path.exists(cls_test_path): os.makedirs(cls_test_path) with open(split_files, "r") as f: split_list = f.readlines() for line in split_list: video_name, label = line.split() video_name = video_name.split(".")[0] cur_path = os.path.join(root_path, class_name, video_name) if int(label) == 1: train_cnt += 1 des_path = os.path.join(target_train_path, class_name, video_name) shutil.move(cur_path, des_path) elif int(label) == 2: test_cnt += 1 des_path = os.path.join(target_test_path, class_name, video_name) shutil.move(cur_path, des_path) print("Split 1: \n Train: {}\n Test: {}".format(train_cnt, test_cnt))
true
true
f72760a70f1f2dd346effdba76e317afc3c4c200
458
py
Python
Tests/misc/eexec_test.py
odidev/fonttools
27b5f568f562971d7fbf64eeb027ea61e4939db4
[ "Apache-2.0", "MIT" ]
2,705
2016-09-27T10:02:12.000Z
2022-03-31T09:37:46.000Z
Tests/misc/eexec_test.py
odidev/fonttools
27b5f568f562971d7fbf64eeb027ea61e4939db4
[ "Apache-2.0", "MIT" ]
1,599
2016-09-27T09:07:36.000Z
2022-03-31T23:04:51.000Z
Tests/misc/eexec_test.py
odidev/fonttools
27b5f568f562971d7fbf64eeb027ea61e4939db4
[ "Apache-2.0", "MIT" ]
352
2016-10-07T04:18:15.000Z
2022-03-30T07:35:01.000Z
from fontTools.misc.eexec import decrypt, encrypt def test_decrypt(): testStr = b"\0\0asdadads asds\265" decryptedStr, R = decrypt(testStr, 12321) assert decryptedStr == b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1' assert R == 36142 def test_encrypt(): testStr = b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1' encryptedStr, R = encrypt(testStr, 12321) assert encryptedStr == b"\0\0asdadads asds\265" assert R == 36142
28.625
74
0.68559
from fontTools.misc.eexec import decrypt, encrypt def test_decrypt(): testStr = b"\0\0asdadads asds\265" decryptedStr, R = decrypt(testStr, 12321) assert decryptedStr == b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1' assert R == 36142 def test_encrypt(): testStr = b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1' encryptedStr, R = encrypt(testStr, 12321) assert encryptedStr == b"\0\0asdadads asds\265" assert R == 36142
true
true
f7276149bae5156f7cb9fe99fd0ec9a0e37e83ee
2,019
py
Python
jigsaw/migrations/0004_auto_20160315_2014.py
sxyu/Jiggly
af705453902b11d7bc1f298dce4698fdc9a470fe
[ "FSFAP" ]
3
2018-03-29T13:31:31.000Z
2022-02-26T04:49:40.000Z
jigsaw/migrations/0004_auto_20160315_2014.py
sxyu/Jiggly
af705453902b11d7bc1f298dce4698fdc9a470fe
[ "FSFAP" ]
null
null
null
jigsaw/migrations/0004_auto_20160315_2014.py
sxyu/Jiggly
af705453902b11d7bc1f298dce4698fdc9a470fe
[ "FSFAP" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-03-16 03:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import jigsaw.models class Migration(migrations.Migration): dependencies = [ ('jigsaw', '0003_auto_20160315_1733'), ] operations = [ migrations.CreateModel( name='GameInstance', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('public', models.BooleanField(default=False)), ('totaltime', models.IntegerField(default=1800)), ('passedtime', models.IntegerField(default=0, editable=False)), ], ), migrations.CreateModel( name='PrintDocument', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('key', models.CharField(default=jigsaw.models._createId, max_length=32)), ('time', models.DateTimeField(auto_now_add=True)), ('round', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='prints', to='jigsaw.Round')), ], ), migrations.RemoveField( model_name='game', name='public', ), migrations.RemoveField( model_name='player', name='game', ), migrations.AddField( model_name='gameinstance', name='game', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='instances', to='jigsaw.Game'), ), migrations.AddField( model_name='player', name='instance', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='players', to='jigsaw.GameInstance'), preserve_default=False, ), ]
36.709091
142
0.592372
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import jigsaw.models class Migration(migrations.Migration): dependencies = [ ('jigsaw', '0003_auto_20160315_1733'), ] operations = [ migrations.CreateModel( name='GameInstance', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('public', models.BooleanField(default=False)), ('totaltime', models.IntegerField(default=1800)), ('passedtime', models.IntegerField(default=0, editable=False)), ], ), migrations.CreateModel( name='PrintDocument', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('key', models.CharField(default=jigsaw.models._createId, max_length=32)), ('time', models.DateTimeField(auto_now_add=True)), ('round', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='prints', to='jigsaw.Round')), ], ), migrations.RemoveField( model_name='game', name='public', ), migrations.RemoveField( model_name='player', name='game', ), migrations.AddField( model_name='gameinstance', name='game', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='instances', to='jigsaw.Game'), ), migrations.AddField( model_name='player', name='instance', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='players', to='jigsaw.GameInstance'), preserve_default=False, ), ]
true
true
f727619381755861c088ab5d8fb34a9eb7540f17
341
py
Python
LC/27.py
szhu3210/LeetCode_Solutions
64747eb172c2ecb3c889830246f3282669516e10
[ "MIT" ]
2
2018-02-24T17:20:02.000Z
2018-02-24T17:25:43.000Z
LC/27.py
szhu3210/LeetCode_Solutions
64747eb172c2ecb3c889830246f3282669516e10
[ "MIT" ]
null
null
null
LC/27.py
szhu3210/LeetCode_Solutions
64747eb172c2ecb3c889830246f3282669516e10
[ "MIT" ]
null
null
null
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ a=0 x=0 while(x<len(nums)): if nums[x]==val: nums.pop(x) x-=1 x+=1 return len(nums)
21.3125
39
0.384164
class Solution(object): def removeElement(self, nums, val): a=0 x=0 while(x<len(nums)): if nums[x]==val: nums.pop(x) x-=1 x+=1 return len(nums)
true
true
f727626a0369587c267d59e56782c18664512665
11,871
py
Python
django/contrib/admin/util.py
t11e/django
447f5375d378dba3bac1ded0306fa0d1b8ab55a4
[ "BSD-3-Clause" ]
1
2016-05-08T13:32:33.000Z
2016-05-08T13:32:33.000Z
django/contrib/admin/util.py
t11e/django
447f5375d378dba3bac1ded0306fa0d1b8ab55a4
[ "BSD-3-Clause" ]
null
null
null
django/contrib/admin/util.py
t11e/django
447f5375d378dba3bac1ded0306fa0d1b8ab55a4
[ "BSD-3-Clause" ]
null
null
null
from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.utils import formats from django.utils.html import escape from django.utils.safestring import mark_safe from django.utils.text import capfirst from django.utils.encoding import force_unicode, smart_unicode, smart_str from django.utils.translation import ungettext, ugettext as _ from django.core.urlresolvers import reverse, NoReverseMatch from django.utils.datastructures import SortedDict def quote(s): """ Ensure that primary key values do not confuse the admin URLs by escaping any '/', '_' and ':' characters. Similar to urllib.quote, except that the quoting is slightly different so that it doesn't get automatically unquoted by the Web browser. """ if not isinstance(s, basestring): return s res = list(s) for i in range(len(res)): c = res[i] if c in """:/_#?;@&=+$,"<>%\\""": res[i] = '_%02X' % ord(c) return ''.join(res) def unquote(s): """ Undo the effects of quote(). Based heavily on urllib.unquote(). """ mychr = chr myatoi = int list = s.split('_') res = [list[0]] myappend = res.append del list[0] for item in list: if item[1:2]: try: myappend(mychr(myatoi(item[:2], 16)) + item[2:]) except ValueError: myappend('_' + item) else: myappend('_' + item) return "".join(res) def flatten_fieldsets(fieldsets): """Returns a list of field names from an admin fieldsets structure.""" field_names = [] for name, opts in fieldsets: for field in opts['fields']: # type checking feels dirty, but it seems like the best way here if type(field) == tuple: field_names.extend(field) else: field_names.append(field) return field_names def _format_callback(obj, user, admin_site, levels_to_root, perms_needed): has_admin = obj.__class__ in admin_site._registry opts = obj._meta try: admin_url = reverse('%s:%s_%s_change' % (admin_site.name, opts.app_label, opts.object_name.lower()), None, (quote(obj._get_pk_val()),)) except NoReverseMatch: admin_url = '%s%s/%s/%s/' % ('../'*levels_to_root, opts.app_label, opts.object_name.lower(), quote(obj._get_pk_val())) if has_admin: p = '%s.%s' % (opts.app_label, opts.get_delete_permission()) if not user.has_perm(p): perms_needed.add(opts.verbose_name) # Display a link to the admin page. return mark_safe(u'%s: <a href="%s">%s</a>' % (escape(capfirst(opts.verbose_name)), admin_url, escape(obj))) else: # Don't display link to edit, because it either has no # admin or is edited inline. return u'%s: %s' % (capfirst(opts.verbose_name), force_unicode(obj)) def get_deleted_objects(objs, opts, user, admin_site, levels_to_root=4): """ Find all objects related to ``objs`` that should also be deleted. ``objs`` should be an iterable of objects. Returns a nested list of strings suitable for display in the template with the ``unordered_list`` filter. `levels_to_root` defines the number of directories (../) to reach the admin root path. In a change_view this is 4, in a change_list view 2. This is for backwards compatibility since the options.delete_selected method uses this function also from a change_list view. This will not be used if we can reverse the URL. """ collector = NestedObjects() for obj in objs: # TODO using a private model API! obj._collect_sub_objects(collector) perms_needed = set() to_delete = collector.nested(_format_callback, user=user, admin_site=admin_site, levels_to_root=levels_to_root, perms_needed=perms_needed) return to_delete, perms_needed class NestedObjects(object): """ A directed acyclic graph collection that exposes the add() API expected by Model._collect_sub_objects and can present its data as a nested list of objects. """ def __init__(self): # Use object keys of the form (model, pk) because actual model # objects may not be unique # maps object key to list of child keys self.children = SortedDict() # maps object key to parent key self.parents = SortedDict() # maps object key to actual object self.seen = SortedDict() def add(self, model, pk, obj, parent_model=None, parent_obj=None, nullable=False): """ Add item ``obj`` to the graph. Returns True (and does nothing) if the item has been seen already. The ``parent_obj`` argument must already exist in the graph; if not, it's ignored (but ``obj`` is still added with no parent). In any case, Model._collect_sub_objects (for whom this API exists) will never pass a parent that hasn't already been added itself. These restrictions in combination ensure the graph will remain acyclic (but can have multiple roots). ``model``, ``pk``, and ``parent_model`` arguments are ignored in favor of the appropriate lookups on ``obj`` and ``parent_obj``; unlike CollectedObjects, we can't maintain independence from the knowledge that we're operating on model instances, and we don't want to allow for inconsistency. ``nullable`` arg is ignored: it doesn't affect how the tree of collected objects should be nested for display. """ model, pk = type(obj), obj._get_pk_val() # auto-created M2M models don't interest us if model._meta.auto_created: return True key = model, pk if key in self.seen: return True self.seen.setdefault(key, obj) if parent_obj is not None: parent_model, parent_pk = (type(parent_obj), parent_obj._get_pk_val()) parent_key = (parent_model, parent_pk) if parent_key in self.seen: self.children.setdefault(parent_key, list()).append(key) self.parents.setdefault(key, parent_key) def _nested(self, key, format_callback=None, **kwargs): obj = self.seen[key] if format_callback: ret = [format_callback(obj, **kwargs)] else: ret = [obj] children = [] for child in self.children.get(key, ()): children.extend(self._nested(child, format_callback, **kwargs)) if children: ret.append(children) return ret def nested(self, format_callback=None, **kwargs): """ Return the graph as a nested list. Passes **kwargs back to the format_callback as kwargs. """ roots = [] for key in self.seen.keys(): if key not in self.parents: roots.extend(self._nested(key, format_callback, **kwargs)) return roots def model_format_dict(obj): """ Return a `dict` with keys 'verbose_name' and 'verbose_name_plural', typically for use with string formatting. `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance. """ if isinstance(obj, (models.Model, models.base.ModelBase)): opts = obj._meta elif isinstance(obj, models.query.QuerySet): opts = obj.model._meta else: opts = obj return { 'verbose_name': force_unicode(opts.verbose_name), 'verbose_name_plural': force_unicode(opts.verbose_name_plural) } def model_ngettext(obj, n=None): """ Return the appropriate `verbose_name` or `verbose_name_plural` value for `obj` depending on the count `n`. `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance. If `obj` is a `QuerySet` instance, `n` is optional and the length of the `QuerySet` is used. """ if isinstance(obj, models.query.QuerySet): if n is None: n = obj.count() obj = obj.model d = model_format_dict(obj) singular, plural = d["verbose_name"], d["verbose_name_plural"] return ungettext(singular, plural, n or 0) def lookup_field(name, obj, model_admin=None): opts = obj._meta try: f = opts.get_field(name) except models.FieldDoesNotExist: # For non-field values, the value is either a method, property or # returned via a callable. if callable(name): attr = name value = attr(obj) elif (model_admin is not None and hasattr(model_admin, name) and not name == '__str__' and not name == '__unicode__'): attr = getattr(model_admin, name) value = attr(obj) else: attr = getattr(obj, name) if callable(attr): value = attr() else: value = attr f = None else: attr = None value = getattr(obj, name) return f, attr, value def label_for_field(name, model, model_admin=None, return_attr=False): attr = None try: label = model._meta.get_field_by_name(name)[0].verbose_name except models.FieldDoesNotExist: if name == "__unicode__": label = force_unicode(model._meta.verbose_name) elif name == "__str__": label = smart_str(model._meta.verbose_name) else: if callable(name): attr = name elif model_admin is not None and hasattr(model_admin, name): attr = getattr(model_admin, name) elif hasattr(model, name): attr = getattr(model, name) else: message = "Unable to lookup '%s' on %s" % (name, model._meta.object_name) if model_admin: message += " or %s" % (model_admin.__name__,) raise AttributeError(message) if hasattr(attr, "short_description"): label = attr.short_description elif callable(attr): if attr.__name__ == "<lambda>": label = "--" else: label = attr.__name__ else: label = name if return_attr: return (label, attr) else: return label def display_for_field(value, field): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return _boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateField) or isinstance(field, models.TimeField): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) else: return smart_unicode(value)
35.435821
94
0.598602
from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.utils import formats from django.utils.html import escape from django.utils.safestring import mark_safe from django.utils.text import capfirst from django.utils.encoding import force_unicode, smart_unicode, smart_str from django.utils.translation import ungettext, ugettext as _ from django.core.urlresolvers import reverse, NoReverseMatch from django.utils.datastructures import SortedDict def quote(s): if not isinstance(s, basestring): return s res = list(s) for i in range(len(res)): c = res[i] if c in """:/_#?;@&=+$,"<>%\\""": res[i] = '_%02X' % ord(c) return ''.join(res) def unquote(s): mychr = chr myatoi = int list = s.split('_') res = [list[0]] myappend = res.append del list[0] for item in list: if item[1:2]: try: myappend(mychr(myatoi(item[:2], 16)) + item[2:]) except ValueError: myappend('_' + item) else: myappend('_' + item) return "".join(res) def flatten_fieldsets(fieldsets): field_names = [] for name, opts in fieldsets: for field in opts['fields']: # type checking feels dirty, but it seems like the best way here if type(field) == tuple: field_names.extend(field) else: field_names.append(field) return field_names def _format_callback(obj, user, admin_site, levels_to_root, perms_needed): has_admin = obj.__class__ in admin_site._registry opts = obj._meta try: admin_url = reverse('%s:%s_%s_change' % (admin_site.name, opts.app_label, opts.object_name.lower()), None, (quote(obj._get_pk_val()),)) except NoReverseMatch: admin_url = '%s%s/%s/%s/' % ('../'*levels_to_root, opts.app_label, opts.object_name.lower(), quote(obj._get_pk_val())) if has_admin: p = '%s.%s' % (opts.app_label, opts.get_delete_permission()) if not user.has_perm(p): perms_needed.add(opts.verbose_name) # Display a link to the admin page. return mark_safe(u'%s: <a href="%s">%s</a>' % (escape(capfirst(opts.verbose_name)), admin_url, escape(obj))) else: # Don't display link to edit, because it either has no # admin or is edited inline. return u'%s: %s' % (capfirst(opts.verbose_name), force_unicode(obj)) def get_deleted_objects(objs, opts, user, admin_site, levels_to_root=4): collector = NestedObjects() for obj in objs: # TODO using a private model API! obj._collect_sub_objects(collector) perms_needed = set() to_delete = collector.nested(_format_callback, user=user, admin_site=admin_site, levels_to_root=levels_to_root, perms_needed=perms_needed) return to_delete, perms_needed class NestedObjects(object): def __init__(self): # Use object keys of the form (model, pk) because actual model # objects may not be unique # maps object key to list of child keys self.children = SortedDict() # maps object key to parent key self.parents = SortedDict() # maps object key to actual object self.seen = SortedDict() def add(self, model, pk, obj, parent_model=None, parent_obj=None, nullable=False): model, pk = type(obj), obj._get_pk_val() # auto-created M2M models don't interest us if model._meta.auto_created: return True key = model, pk if key in self.seen: return True self.seen.setdefault(key, obj) if parent_obj is not None: parent_model, parent_pk = (type(parent_obj), parent_obj._get_pk_val()) parent_key = (parent_model, parent_pk) if parent_key in self.seen: self.children.setdefault(parent_key, list()).append(key) self.parents.setdefault(key, parent_key) def _nested(self, key, format_callback=None, **kwargs): obj = self.seen[key] if format_callback: ret = [format_callback(obj, **kwargs)] else: ret = [obj] children = [] for child in self.children.get(key, ()): children.extend(self._nested(child, format_callback, **kwargs)) if children: ret.append(children) return ret def nested(self, format_callback=None, **kwargs): roots = [] for key in self.seen.keys(): if key not in self.parents: roots.extend(self._nested(key, format_callback, **kwargs)) return roots def model_format_dict(obj): if isinstance(obj, (models.Model, models.base.ModelBase)): opts = obj._meta elif isinstance(obj, models.query.QuerySet): opts = obj.model._meta else: opts = obj return { 'verbose_name': force_unicode(opts.verbose_name), 'verbose_name_plural': force_unicode(opts.verbose_name_plural) } def model_ngettext(obj, n=None): if isinstance(obj, models.query.QuerySet): if n is None: n = obj.count() obj = obj.model d = model_format_dict(obj) singular, plural = d["verbose_name"], d["verbose_name_plural"] return ungettext(singular, plural, n or 0) def lookup_field(name, obj, model_admin=None): opts = obj._meta try: f = opts.get_field(name) except models.FieldDoesNotExist: # For non-field values, the value is either a method, property or # returned via a callable. if callable(name): attr = name value = attr(obj) elif (model_admin is not None and hasattr(model_admin, name) and not name == '__str__' and not name == '__unicode__'): attr = getattr(model_admin, name) value = attr(obj) else: attr = getattr(obj, name) if callable(attr): value = attr() else: value = attr f = None else: attr = None value = getattr(obj, name) return f, attr, value def label_for_field(name, model, model_admin=None, return_attr=False): attr = None try: label = model._meta.get_field_by_name(name)[0].verbose_name except models.FieldDoesNotExist: if name == "__unicode__": label = force_unicode(model._meta.verbose_name) elif name == "__str__": label = smart_str(model._meta.verbose_name) else: if callable(name): attr = name elif model_admin is not None and hasattr(model_admin, name): attr = getattr(model_admin, name) elif hasattr(model, name): attr = getattr(model, name) else: message = "Unable to lookup '%s' on %s" % (name, model._meta.object_name) if model_admin: message += " or %s" % (model_admin.__name__,) raise AttributeError(message) if hasattr(attr, "short_description"): label = attr.short_description elif callable(attr): if attr.__name__ == "<lambda>": label = "--" else: label = attr.__name__ else: label = name if return_attr: return (label, attr) else: return label def display_for_field(value, field): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return _boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateField) or isinstance(field, models.TimeField): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) else: return smart_unicode(value)
true
true
f72762d80e22c0940fd6c0b7df91a5eb5427ea3d
18,819
py
Python
log_complete/model_403.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
log_complete/model_403.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
log_complete/model_403.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
# exported from PySB model 'model' from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD Model() Monomer('Ligand', ['Receptor']) Monomer('ParpU', ['C3A']) Monomer('C8A', ['BidU', 'C3pro']) Monomer('SmacM', ['BaxA']) Monomer('BaxM', ['BidM', 'BaxA']) Monomer('Apop', ['C3pro', 'Xiap']) Monomer('Fadd', ['Receptor', 'C8pro']) Monomer('SmacC', ['Xiap']) Monomer('ParpC') Monomer('Xiap', ['SmacC', 'Apop', 'C3A']) Monomer('C9') Monomer('C3ub') Monomer('C8pro', ['Fadd', 'C6A']) Monomer('C6A', ['C8pro']) Monomer('C3pro', ['Apop', 'C8A']) Monomer('CytoCM', ['BaxA']) Monomer('CytoCC') Monomer('BaxA', ['BaxM', 'BaxA_1', 'BaxA_2', 'SmacM', 'CytoCM']) Monomer('ApafI') Monomer('BidU', ['C8A']) Monomer('BidT') Monomer('C3A', ['Xiap', 'ParpU', 'C6pro']) Monomer('ApafA') Monomer('BidM', ['BaxM']) Monomer('Receptor', ['Ligand', 'Fadd']) Monomer('C6pro', ['C3A']) Parameter('bind_0_Ligand_binder_Receptor_binder_target_2kf', 1.0) Parameter('bind_0_Ligand_binder_Receptor_binder_target_1kr', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_2kf', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_1kr', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr', 1.0) Parameter('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr', 1.0) Parameter('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc', 1.0) Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf', 1.0) Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr', 1.0) Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf', 1.0) Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr', 1.0) Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0) Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0) Parameter('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0) Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf', 1.0) Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr', 1.0) Parameter('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr', 1.0) Parameter('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kf', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kr', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr', 1.0) Parameter('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr', 1.0) Parameter('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc', 1.0) Parameter('pore_formation_0_BaxA_pore_2kf', 1.0) Parameter('pore_formation_0_BaxA_pore_1kr', 1.0) Parameter('pore_formation_1_BaxA_pore_2kf', 1.0) Parameter('pore_formation_1_BaxA_pore_1kr', 1.0) Parameter('pore_formation_2_BaxA_pore_2kf', 1.0) Parameter('pore_formation_2_BaxA_pore_1kr', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr', 1.0) Parameter('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc', 1.0) Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf', 1.0) Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr', 1.0) Parameter('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc', 1.0) Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0) Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0) Parameter('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0) Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf', 1.0) Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr', 1.0) Parameter('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc', 1.0) Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf', 1.0) Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr', 1.0) Parameter('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0) Parameter('Ligand_0', 1000.0) Parameter('ParpU_0', 1000000.0) Parameter('C8A_0', 0.0) Parameter('SmacM_0', 100000.0) Parameter('BaxM_0', 40000.0) Parameter('Apop_0', 0.0) Parameter('Fadd_0', 130000.0) Parameter('SmacC_0', 0.0) Parameter('ParpC_0', 0.0) Parameter('Xiap_0', 100750.0) Parameter('C9_0', 100000.0) Parameter('C3ub_0', 0.0) Parameter('C8pro_0', 130000.0) Parameter('C6A_0', 0.0) Parameter('C3pro_0', 21000.0) Parameter('CytoCM_0', 500000.0) Parameter('CytoCC_0', 0.0) Parameter('BaxA_0', 0.0) Parameter('ApafI_0', 100000.0) Parameter('BidU_0', 171000.0) Parameter('BidT_0', 0.0) Parameter('C3A_0', 0.0) Parameter('ApafA_0', 0.0) Parameter('BidM_0', 0.0) Parameter('Receptor_0', 100.0) Parameter('C6pro_0', 100.0) Observable('Ligand_obs', Ligand()) Observable('ParpU_obs', ParpU()) Observable('C8A_obs', C8A()) Observable('SmacM_obs', SmacM()) Observable('BaxM_obs', BaxM()) Observable('Apop_obs', Apop()) Observable('Fadd_obs', Fadd()) Observable('SmacC_obs', SmacC()) Observable('ParpC_obs', ParpC()) Observable('Xiap_obs', Xiap()) Observable('C9_obs', C9()) Observable('C3ub_obs', C3ub()) Observable('C8pro_obs', C8pro()) Observable('C6A_obs', C6A()) Observable('C3pro_obs', C3pro()) Observable('CytoCM_obs', CytoCM()) Observable('CytoCC_obs', CytoCC()) Observable('BaxA_obs', BaxA()) Observable('ApafI_obs', ApafI()) Observable('BidU_obs', BidU()) Observable('BidT_obs', BidT()) Observable('C3A_obs', C3A()) Observable('ApafA_obs', ApafA()) Observable('BidM_obs', BidM()) Observable('Receptor_obs', Receptor()) Observable('C6pro_obs', C6pro()) Rule('bind_0_Ligand_binder_Receptor_binder_target', Ligand(Receptor=None) + Receptor(Ligand=None, Fadd=None) | Ligand(Receptor=1) % Receptor(Ligand=1, Fadd=None), bind_0_Ligand_binder_Receptor_binder_target_2kf, bind_0_Ligand_binder_Receptor_binder_target_1kr) Rule('bind_0_Receptor_binder_Fadd_binder_target', Receptor(Ligand=ANY, Fadd=None) + Fadd(Receptor=None, C8pro=None) | Receptor(Ligand=ANY, Fadd=1) % Fadd(Receptor=1, C8pro=None), bind_0_Receptor_binder_Fadd_binder_target_2kf, bind_0_Receptor_binder_Fadd_binder_target_1kr) Rule('substrate_binding_0_Fadd_catalyzer_C8pro_substrate', Fadd(Receptor=ANY, C8pro=None) + C8pro(Fadd=None, C6A=None) | Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None), substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf, substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr) Rule('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product', Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None) >> Fadd(Receptor=ANY, C8pro=None) + C8A(BidU=None, C3pro=None), catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc) Rule('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=None, C3pro=None) + BidU(C8A=None) | C8A(BidU=1, C3pro=None) % BidU(C8A=1), catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf, catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr) Rule('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=1, C3pro=None) % BidU(C8A=1) >> C8A(BidU=None, C3pro=None) + BidT(), catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc) Rule('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex', ApafI() + CytoCC() | ApafA(), conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf, conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr) Rule('inhibition_0_SmacC_inhibitor_Xiap_inh_target', SmacC(Xiap=None) + Xiap(SmacC=None, Apop=None, C3A=None) | SmacC(Xiap=1) % Xiap(SmacC=1, Apop=None, C3A=None), inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf, inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr) Rule('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex', ApafA() + C9() | Apop(C3pro=None, Xiap=None), conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf, conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr) Rule('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=None, Xiap=None) + C3pro(Apop=None, C8A=None) | Apop(C3pro=1, Xiap=None) % C3pro(Apop=1, C8A=None), catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr) Rule('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=1, Xiap=None) % C3pro(Apop=1, C8A=None) >> Apop(C3pro=None, Xiap=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc) Rule('inhibition_0_Xiap_inhibitor_Apop_inh_target', Xiap(SmacC=None, Apop=None, C3A=None) + Apop(C3pro=None, Xiap=None) | Xiap(SmacC=None, Apop=1, C3A=None) % Apop(C3pro=None, Xiap=1), inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf, inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr) Rule('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=None) + C3A(Xiap=None, ParpU=None, C6pro=None) | Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None), catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf, catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr) Rule('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None) >> Xiap(SmacC=None, Apop=None, C3A=None) + C3ub(), catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc) Rule('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=None, C6pro=None) + ParpU(C3A=None) | C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1), catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf, catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr) Rule('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + ParpC(), catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc) Rule('equilibration_0_BidT_equil_a_BidM_equil_b', BidT() | BidM(BaxM=None), equilibration_0_BidT_equil_a_BidM_equil_b_1kf, equilibration_0_BidT_equil_a_BidM_equil_b_1kr) Rule('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=None) + BaxM(BidM=None, BaxA=None) | BidM(BaxM=1) % BaxM(BidM=1, BaxA=None), catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf, catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr) Rule('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=1) % BaxM(BidM=1, BaxA=None) >> BidM(BaxM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc) Rule('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxM(BidM=None, BaxA=None) | BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1), self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf, self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr) Rule('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1) >> BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc) Rule('pore_formation_0_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None), pore_formation_0_BaxA_pore_2kf, pore_formation_0_BaxA_pore_1kr) Rule('pore_formation_1_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None), pore_formation_1_BaxA_pore_2kf, pore_formation_1_BaxA_pore_1kr) Rule('pore_formation_2_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None), pore_formation_2_BaxA_pore_2kf, pore_formation_2_BaxA_pore_1kr) Rule('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5), transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf, transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr) Rule('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacC(Xiap=None), transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc) Rule('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5), transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf, transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr) Rule('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCC(), transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc) Rule('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=None) + C3pro(Apop=None, C8A=None) | C8A(BidU=None, C3pro=1) % C3pro(Apop=None, C8A=1), catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr) Rule('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=1) % C3pro(Apop=None, C8A=1) >> C8A(BidU=None, C3pro=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc) Rule('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=None) + C6pro(C3A=None) | C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1), catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf, catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr) Rule('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + C6A(C8pro=None), catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc) Rule('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=None) + C8pro(Fadd=None, C6A=None) | C6A(C8pro=1) % C8pro(Fadd=None, C6A=1), catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf, catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr) Rule('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=1) % C8pro(Fadd=None, C6A=1) >> C6A(C8pro=None) + C8A(BidU=None, C3pro=None), catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc) Initial(Ligand(Receptor=None), Ligand_0) Initial(ParpU(C3A=None), ParpU_0) Initial(C8A(BidU=None, C3pro=None), C8A_0) Initial(SmacM(BaxA=None), SmacM_0) Initial(BaxM(BidM=None, BaxA=None), BaxM_0) Initial(Apop(C3pro=None, Xiap=None), Apop_0) Initial(Fadd(Receptor=None, C8pro=None), Fadd_0) Initial(SmacC(Xiap=None), SmacC_0) Initial(ParpC(), ParpC_0) Initial(Xiap(SmacC=None, Apop=None, C3A=None), Xiap_0) Initial(C9(), C9_0) Initial(C3ub(), C3ub_0) Initial(C8pro(Fadd=None, C6A=None), C8pro_0) Initial(C6A(C8pro=None), C6A_0) Initial(C3pro(Apop=None, C8A=None), C3pro_0) Initial(CytoCM(BaxA=None), CytoCM_0) Initial(CytoCC(), CytoCC_0) Initial(BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), BaxA_0) Initial(ApafI(), ApafI_0) Initial(BidU(C8A=None), BidU_0) Initial(BidT(), BidT_0) Initial(C3A(Xiap=None, ParpU=None, C6pro=None), C3A_0) Initial(ApafA(), ApafA_0) Initial(BidM(BaxM=None), BidM_0) Initial(Receptor(Ligand=None, Fadd=None), Receptor_0) Initial(C6pro(C3A=None), C6pro_0)
91.354369
710
0.806525
from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD Model() Monomer('Ligand', ['Receptor']) Monomer('ParpU', ['C3A']) Monomer('C8A', ['BidU', 'C3pro']) Monomer('SmacM', ['BaxA']) Monomer('BaxM', ['BidM', 'BaxA']) Monomer('Apop', ['C3pro', 'Xiap']) Monomer('Fadd', ['Receptor', 'C8pro']) Monomer('SmacC', ['Xiap']) Monomer('ParpC') Monomer('Xiap', ['SmacC', 'Apop', 'C3A']) Monomer('C9') Monomer('C3ub') Monomer('C8pro', ['Fadd', 'C6A']) Monomer('C6A', ['C8pro']) Monomer('C3pro', ['Apop', 'C8A']) Monomer('CytoCM', ['BaxA']) Monomer('CytoCC') Monomer('BaxA', ['BaxM', 'BaxA_1', 'BaxA_2', 'SmacM', 'CytoCM']) Monomer('ApafI') Monomer('BidU', ['C8A']) Monomer('BidT') Monomer('C3A', ['Xiap', 'ParpU', 'C6pro']) Monomer('ApafA') Monomer('BidM', ['BaxM']) Monomer('Receptor', ['Ligand', 'Fadd']) Monomer('C6pro', ['C3A']) Parameter('bind_0_Ligand_binder_Receptor_binder_target_2kf', 1.0) Parameter('bind_0_Ligand_binder_Receptor_binder_target_1kr', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_2kf', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_1kr', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr', 1.0) Parameter('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr', 1.0) Parameter('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc', 1.0) Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf', 1.0) Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr', 1.0) Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf', 1.0) Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr', 1.0) Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0) Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0) Parameter('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0) Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf', 1.0) Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr', 1.0) Parameter('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr', 1.0) Parameter('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kf', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kr', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr', 1.0) Parameter('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr', 1.0) Parameter('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc', 1.0) Parameter('pore_formation_0_BaxA_pore_2kf', 1.0) Parameter('pore_formation_0_BaxA_pore_1kr', 1.0) Parameter('pore_formation_1_BaxA_pore_2kf', 1.0) Parameter('pore_formation_1_BaxA_pore_1kr', 1.0) Parameter('pore_formation_2_BaxA_pore_2kf', 1.0) Parameter('pore_formation_2_BaxA_pore_1kr', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr', 1.0) Parameter('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc', 1.0) Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf', 1.0) Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr', 1.0) Parameter('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc', 1.0) Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0) Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0) Parameter('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0) Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf', 1.0) Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr', 1.0) Parameter('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc', 1.0) Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf', 1.0) Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr', 1.0) Parameter('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0) Parameter('Ligand_0', 1000.0) Parameter('ParpU_0', 1000000.0) Parameter('C8A_0', 0.0) Parameter('SmacM_0', 100000.0) Parameter('BaxM_0', 40000.0) Parameter('Apop_0', 0.0) Parameter('Fadd_0', 130000.0) Parameter('SmacC_0', 0.0) Parameter('ParpC_0', 0.0) Parameter('Xiap_0', 100750.0) Parameter('C9_0', 100000.0) Parameter('C3ub_0', 0.0) Parameter('C8pro_0', 130000.0) Parameter('C6A_0', 0.0) Parameter('C3pro_0', 21000.0) Parameter('CytoCM_0', 500000.0) Parameter('CytoCC_0', 0.0) Parameter('BaxA_0', 0.0) Parameter('ApafI_0', 100000.0) Parameter('BidU_0', 171000.0) Parameter('BidT_0', 0.0) Parameter('C3A_0', 0.0) Parameter('ApafA_0', 0.0) Parameter('BidM_0', 0.0) Parameter('Receptor_0', 100.0) Parameter('C6pro_0', 100.0) Observable('Ligand_obs', Ligand()) Observable('ParpU_obs', ParpU()) Observable('C8A_obs', C8A()) Observable('SmacM_obs', SmacM()) Observable('BaxM_obs', BaxM()) Observable('Apop_obs', Apop()) Observable('Fadd_obs', Fadd()) Observable('SmacC_obs', SmacC()) Observable('ParpC_obs', ParpC()) Observable('Xiap_obs', Xiap()) Observable('C9_obs', C9()) Observable('C3ub_obs', C3ub()) Observable('C8pro_obs', C8pro()) Observable('C6A_obs', C6A()) Observable('C3pro_obs', C3pro()) Observable('CytoCM_obs', CytoCM()) Observable('CytoCC_obs', CytoCC()) Observable('BaxA_obs', BaxA()) Observable('ApafI_obs', ApafI()) Observable('BidU_obs', BidU()) Observable('BidT_obs', BidT()) Observable('C3A_obs', C3A()) Observable('ApafA_obs', ApafA()) Observable('BidM_obs', BidM()) Observable('Receptor_obs', Receptor()) Observable('C6pro_obs', C6pro()) Rule('bind_0_Ligand_binder_Receptor_binder_target', Ligand(Receptor=None) + Receptor(Ligand=None, Fadd=None) | Ligand(Receptor=1) % Receptor(Ligand=1, Fadd=None), bind_0_Ligand_binder_Receptor_binder_target_2kf, bind_0_Ligand_binder_Receptor_binder_target_1kr) Rule('bind_0_Receptor_binder_Fadd_binder_target', Receptor(Ligand=ANY, Fadd=None) + Fadd(Receptor=None, C8pro=None) | Receptor(Ligand=ANY, Fadd=1) % Fadd(Receptor=1, C8pro=None), bind_0_Receptor_binder_Fadd_binder_target_2kf, bind_0_Receptor_binder_Fadd_binder_target_1kr) Rule('substrate_binding_0_Fadd_catalyzer_C8pro_substrate', Fadd(Receptor=ANY, C8pro=None) + C8pro(Fadd=None, C6A=None) | Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None), substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf, substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr) Rule('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product', Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None) >> Fadd(Receptor=ANY, C8pro=None) + C8A(BidU=None, C3pro=None), catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc) Rule('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=None, C3pro=None) + BidU(C8A=None) | C8A(BidU=1, C3pro=None) % BidU(C8A=1), catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf, catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr) Rule('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=1, C3pro=None) % BidU(C8A=1) >> C8A(BidU=None, C3pro=None) + BidT(), catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc) Rule('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex', ApafI() + CytoCC() | ApafA(), conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf, conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr) Rule('inhibition_0_SmacC_inhibitor_Xiap_inh_target', SmacC(Xiap=None) + Xiap(SmacC=None, Apop=None, C3A=None) | SmacC(Xiap=1) % Xiap(SmacC=1, Apop=None, C3A=None), inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf, inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr) Rule('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex', ApafA() + C9() | Apop(C3pro=None, Xiap=None), conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf, conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr) Rule('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=None, Xiap=None) + C3pro(Apop=None, C8A=None) | Apop(C3pro=1, Xiap=None) % C3pro(Apop=1, C8A=None), catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr) Rule('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=1, Xiap=None) % C3pro(Apop=1, C8A=None) >> Apop(C3pro=None, Xiap=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc) Rule('inhibition_0_Xiap_inhibitor_Apop_inh_target', Xiap(SmacC=None, Apop=None, C3A=None) + Apop(C3pro=None, Xiap=None) | Xiap(SmacC=None, Apop=1, C3A=None) % Apop(C3pro=None, Xiap=1), inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf, inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr) Rule('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=None) + C3A(Xiap=None, ParpU=None, C6pro=None) | Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None), catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf, catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr) Rule('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None) >> Xiap(SmacC=None, Apop=None, C3A=None) + C3ub(), catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc) Rule('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=None, C6pro=None) + ParpU(C3A=None) | C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1), catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf, catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr) Rule('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + ParpC(), catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc) Rule('equilibration_0_BidT_equil_a_BidM_equil_b', BidT() | BidM(BaxM=None), equilibration_0_BidT_equil_a_BidM_equil_b_1kf, equilibration_0_BidT_equil_a_BidM_equil_b_1kr) Rule('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=None) + BaxM(BidM=None, BaxA=None) | BidM(BaxM=1) % BaxM(BidM=1, BaxA=None), catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf, catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr) Rule('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=1) % BaxM(BidM=1, BaxA=None) >> BidM(BaxM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc) Rule('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxM(BidM=None, BaxA=None) | BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1), self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf, self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr) Rule('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1) >> BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc) Rule('pore_formation_0_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None), pore_formation_0_BaxA_pore_2kf, pore_formation_0_BaxA_pore_1kr) Rule('pore_formation_1_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None), pore_formation_1_BaxA_pore_2kf, pore_formation_1_BaxA_pore_1kr) Rule('pore_formation_2_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None), pore_formation_2_BaxA_pore_2kf, pore_formation_2_BaxA_pore_1kr) Rule('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5), transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf, transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr) Rule('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacC(Xiap=None), transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc) Rule('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5), transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf, transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr) Rule('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCC(), transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc) Rule('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=None) + C3pro(Apop=None, C8A=None) | C8A(BidU=None, C3pro=1) % C3pro(Apop=None, C8A=1), catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr) Rule('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=1) % C3pro(Apop=None, C8A=1) >> C8A(BidU=None, C3pro=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc) Rule('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=None) + C6pro(C3A=None) | C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1), catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf, catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr) Rule('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + C6A(C8pro=None), catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc) Rule('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=None) + C8pro(Fadd=None, C6A=None) | C6A(C8pro=1) % C8pro(Fadd=None, C6A=1), catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf, catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr) Rule('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=1) % C8pro(Fadd=None, C6A=1) >> C6A(C8pro=None) + C8A(BidU=None, C3pro=None), catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc) Initial(Ligand(Receptor=None), Ligand_0) Initial(ParpU(C3A=None), ParpU_0) Initial(C8A(BidU=None, C3pro=None), C8A_0) Initial(SmacM(BaxA=None), SmacM_0) Initial(BaxM(BidM=None, BaxA=None), BaxM_0) Initial(Apop(C3pro=None, Xiap=None), Apop_0) Initial(Fadd(Receptor=None, C8pro=None), Fadd_0) Initial(SmacC(Xiap=None), SmacC_0) Initial(ParpC(), ParpC_0) Initial(Xiap(SmacC=None, Apop=None, C3A=None), Xiap_0) Initial(C9(), C9_0) Initial(C3ub(), C3ub_0) Initial(C8pro(Fadd=None, C6A=None), C8pro_0) Initial(C6A(C8pro=None), C6A_0) Initial(C3pro(Apop=None, C8A=None), C3pro_0) Initial(CytoCM(BaxA=None), CytoCM_0) Initial(CytoCC(), CytoCC_0) Initial(BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), BaxA_0) Initial(ApafI(), ApafI_0) Initial(BidU(C8A=None), BidU_0) Initial(BidT(), BidT_0) Initial(C3A(Xiap=None, ParpU=None, C6pro=None), C3A_0) Initial(ApafA(), ApafA_0) Initial(BidM(BaxM=None), BidM_0) Initial(Receptor(Ligand=None, Fadd=None), Receptor_0) Initial(C6pro(C3A=None), C6pro_0)
true
true
f72765a52a463ef2846870cae24daa680f1ff6c0
11,200
py
Python
toontown/catalog/CatalogAccessoryItemGlobals.py
CrankySupertoon01/Toontown-2
60893d104528a8e7eb4aced5d0015f22e203466d
[ "MIT" ]
1
2021-02-13T22:40:50.000Z
2021-02-13T22:40:50.000Z
toontown/catalog/CatalogAccessoryItemGlobals.py
CrankySupertoonArchive/Toontown-2
60893d104528a8e7eb4aced5d0015f22e203466d
[ "MIT" ]
1
2018-07-28T20:07:04.000Z
2018-07-30T18:28:34.000Z
toontown/catalog/CatalogAccessoryItemGlobals.py
CrankySupertoonArchive/Toontown-2
60893d104528a8e7eb4aced5d0015f22e203466d
[ "MIT" ]
2
2019-12-02T01:39:10.000Z
2021-02-13T22:41:00.000Z
ATArticle = 0 ATString = 1 ATBasePrice = 2 ATReleased = 3 ATEmblemPrices = 4 AHat = 0 AGlasses = 1 ABackpack = 2 AShoes = 3 APriceBasic = 250 APriceBasicPlus = 400 APriceCool = 800 APriceAwesome = 1500 AccessoryTypes = {101: (AHat, 'hbb1', APriceBasic, 1), 102: (AHat, 'hsf1', APriceCool, 5), 103: (AHat, 'hrb1', APriceBasic, 1), 104: (AHat, 'hsf2', APriceCool, 0), 105: (AHat, 'hsf3', APriceCool, 0), 106: (AHat, 'hrb2', APriceBasicPlus, 3), 107: (AHat, 'hrb3', APriceBasicPlus, 0), 108: (AHat, 'hht1', APriceCool, 4), 109: (AHat, 'hht2', APriceCool, 3), 110: (AHat, 'htp1', APriceCool, 3), 111: (AHat, 'htp2', APriceCool, 0), 112: (AHat, 'hav1', 3500, 0), 113: (AHat, 'hfp1', 3500, 0), 114: (AHat, 'hsg1', 3500, 0), 115: (AHat, 'hwt1', 3500, 0), 116: (AHat, 'hfz1', APriceCool, 5), 117: (AHat, 'hgf1', APriceCool, 1), 118: (AHat, 'hpt1', APriceBasicPlus, 1), 119: (AHat, 'hpb1', APriceBasicPlus, 6), 120: (AHat, 'hcr1', 10000, 5), 121: (AHat, 'hbb2', APriceBasic, 2), 122: (AHat, 'hbb3', APriceBasic, 2), 123: (AHat, 'hcw1', APriceCool, 1), 124: (AHat, 'hpr1', APriceAwesome, 1), 125: (AHat, 'hpp1', APriceBasicPlus, 1), 126: (AHat, 'hfs1', APriceCool, 1), 127: (AHat, 'hsb1', APriceAwesome, 1), 128: (AHat, 'hst1', APriceBasicPlus, 1), 129: (AHat, 'hsu1', APriceCool, 1), 130: (AHat, 'hrb4', APriceBasic, 1), 131: (AHat, 'hrb5', APriceBasicPlus, 4), 132: (AHat, 'hrb6', APriceBasic, 2), 133: (AHat, 'hrb7', APriceBasicPlus, 6), 134: (AHat, 'hat1', APriceCool, 2), 135: (AHat, 'hhd1', APriceCool, 2), 136: (AHat, 'hbw1', APriceCool, 6), 137: (AHat, 'hch1', APriceCool, 5), 138: (AHat, 'hdt1', APriceAwesome, 6), 139: (AHat, 'hft1', APriceCool, 4), 140: (AHat, 'hfd1', APriceCool, 6), 141: (AHat, 'hmk1', APriceAwesome, 2), 142: (AHat, 'hft2', APriceCool, 6), 143: (AHat, 'hhd2', APriceCool, 3), 144: (AHat, 'hpc1', APriceCool, 5), 145: (AHat, 'hrh1', APriceCool, 2), 146: (AHat, 'hhm1', 2500, 2), 147: (AHat, 'hat2', APriceCool, 2), 148: (AHat, 'htr1', 10000, 3), 149: (AHat, 'hhm2', APriceAwesome, 2), 150: (AHat, 'hwz1', APriceCool, 2), 151: (AHat, 'hwz2', APriceCool, 2), 152: (AHat, 'hhm3', APriceAwesome, 6), 153: (AHat, 'hhm4', APriceAwesome, 5), 154: (AHat, 'hfp2', APriceCool, 5), 155: (AHat, 'hhm5', APriceAwesome, 4), 156: (AHat, 'hnp1', APriceAwesome, 6), 157: (AHat, 'hpc2', APriceAwesome, 3), 158: (AHat, 'hph1', APriceAwesome, 4), 159: (AHat, 'hwg1', APriceCool, 5), 160: (AHat, 'hbb4', APriceBasic, 5), 161: (AHat, 'hbb5', APriceBasic, 2), 162: (AHat, 'hbb6', APriceBasic, 5), 163: (AHat, 'hsl1', APriceCool, 5), 164: (AHat, 'hfr1', 3000, 4), 165: (AHat, 'hby1', APriceAwesome, 5), 166: (AHat, 'hrb8', APriceBasicPlus, 6), 167: (AHat, 'hjh1', APriceAwesome, 3), 168: (AHat, 'hbb7', APriceBasic, 6), 169: (AHat, 'hrb9', APriceBasicPlus, 6), 170: (AHat, 'hwt2', APriceAwesome, 4), 171: (AHat, 'hhw1', APriceBasicPlus, 7), 172: (AHat, 'hhw2', 900, 7), 173: (AHat, 'hob1', APriceAwesome, 6), 174: (AHat, 'hbn1', APriceAwesome, 8), 175: (AHat, 'hpt2', APriceCool, 9), 176: (AHat, 'kmh1', APriceAwesome, 8), 201: (AGlasses, 'grd1', APriceBasicPlus, 0), 202: (AGlasses, 'gmb1', APriceCool, 1), 203: (AGlasses, 'gnr1', APriceCool, 0), 204: (AGlasses, 'gst1', APriceBasicPlus, 1), 205: (AGlasses, 'g3d1', APriceCool, 1), 206: (AGlasses, 'gav1', APriceCool, 1), 207: (AGlasses, 'gce1', APriceCool, 2), 208: (AGlasses, 'gdk1', APriceBasic, 1), 209: (AGlasses, 'gjo1', APriceBasicPlus, 1), 210: (AGlasses, 'gsb1', APriceAwesome, 1), 211: (AGlasses, 'ggl1', APriceCool, 6), 212: (AGlasses, 'ggm1', APriceBasicPlus, 2), 213: (AGlasses, 'ghg1', APriceAwesome, 3), 214: (AGlasses, 'gie1', APriceCool, 2), 215: (AGlasses, 'gmt1', APriceCool, 2), 216: (AGlasses, 'gmt2', APriceCool, 2), 217: (AGlasses, 'gmt3', 3500, 5), 218: (AGlasses, 'gmt4', 3500, 5), 219: (AGlasses, 'gmt5', 3500, 5), 220: (AGlasses, 'gmn1', APriceAwesome, 6), 221: (AGlasses, 'gmo1', APriceAwesome, 4), 222: (AGlasses, 'gsr1', APriceBasicPlus, 5), 223: (AGlasses, 'ghw1', APriceBasic, 0), 224: (AGlasses, 'ghw2', APriceBasic, 7), 225: (AGlasses, 'gag1', APriceAwesome, 8), 226: (AGlasses, 'ghy1', APriceAwesome, 8), 301: (ABackpack, 'bpb1', APriceBasic, 4), 302: (ABackpack, 'bpb2', APriceBasic, 1), 303: (ABackpack, 'bpb3', APriceBasic, 5), 304: (ABackpack, 'bpd1', APriceBasicPlus, 4), 305: (ABackpack, 'bpd2', APriceBasicPlus, 5), 306: (ABackpack, 'bwg1', APriceCool, 2), 307: (ABackpack, 'bwg2', APriceCool, 2), 308: (ABackpack, 'bwg3', APriceCool, 1), 309: (ABackpack, 'bst1', APriceAwesome, 1), 310: (ABackpack, 'bfn1', APriceCool, 1), 311: (ABackpack, 'baw1', APriceCool, 3), 312: (ABackpack, 'baw2', APriceAwesome, 2), 313: (ABackpack, 'bwt1', 3000, 3), 314: (ABackpack, 'bwg4', APriceAwesome, 6), 315: (ABackpack, 'bwg5', 3000, 5), 316: (ABackpack, 'bwg6', 3000, 4), 317: (ABackpack, 'bjp1', 3000, 1), 318: (ABackpack, 'blg1', APriceCool, 2), 319: (ABackpack, 'bsa1', 2500, 5), 320: (ABackpack, 'bwg7', APriceAwesome, 6), 321: (ABackpack, 'bsa2', 2000, 2), 322: (ABackpack, 'bsa3', 2000, 2), 323: (ABackpack, 'bap1', 5000, 4), 324: (ABackpack, 'bhw1', 900, 7), 325: (ABackpack, 'bhw2', APriceBasicPlus, 7), 326: (ABackpack, 'bhw3', APriceBasicPlus, 7), 327: (ABackpack, 'bhw4', 900, 7), 328: (ABackpack, 'bob1', 3000, 6), 329: (ABackpack, 'bfg1', 3000, 6), 330: (ABackpack, 'bfl1', APriceAwesome, 8), 401: (AShoes, 'sat1', APriceBasic, 3), 402: (AShoes, 'sat2', APriceBasic, 1), 403: (AShoes, 'smb1', APriceAwesome, 1), 404: (AShoes, 'scs1', APriceBasicPlus, 6), 405: (AShoes, 'swt1', APriceBasicPlus, 1), 406: (AShoes, 'smj1', APriceBasicPlus, 1), 407: (AShoes, 'sdk1', APriceBasic, 1), 408: (AShoes, 'sat3', APriceBasic, 1), 409: (AShoes, 'scs2', APriceBasicPlus, 1), 410: (AShoes, 'scs3', APriceBasicPlus, 1), 411: (AShoes, 'scs4', APriceBasicPlus, 1), 412: (AShoes, 'scb1', APriceAwesome, 1), 413: (AShoes, 'sfb1', APriceCool, 1), 414: (AShoes, 'sht1', APriceAwesome, 4), 415: (AShoes, 'smj2', APriceBasicPlus, 3), 416: (AShoes, 'smj3', APriceBasicPlus, 4), 417: (AShoes, 'ssb1', APriceAwesome, 2), 418: (AShoes, 'sts1', APriceBasic, 5), 419: (AShoes, 'sts2', APriceBasic, 4), 420: (AShoes, 'scs5', APriceBasicPlus, 4), 421: (AShoes, 'smb2', APriceAwesome, 3), 422: (AShoes, 'smb3', APriceAwesome, 2), 423: (AShoes, 'smb4', APriceAwesome, 5), 424: (AShoes, 'sfb2', 2000, 6), 425: (AShoes, 'sfb3', 2000, 4), 426: (AShoes, 'sfb4', 2000, 3), 427: (AShoes, 'sfb5', 2000, 5), 428: (AShoes, 'sfb6', 2000, 4), 429: (AShoes, 'slf1', APriceBasicPlus, 3), 430: (AShoes, 'smj4', APriceBasicPlus, 2), 431: (AShoes, 'smt1', APriceAwesome, 4), 432: (AShoes, 'sox1', APriceAwesome, 5), 433: (AShoes, 'srb1', APriceAwesome, 6), 434: (AShoes, 'sst1', 3000, 3), 435: (AShoes, 'swb1', APriceCool, 3), 436: (AShoes, 'swb2', APriceCool, 4), 437: (AShoes, 'swk1', APriceAwesome, 3), 438: (AShoes, 'scs6', APriceBasicPlus, 0), 439: (AShoes, 'smb5', APriceAwesome, 3), 440: (AShoes, 'sht2', APriceAwesome, 4), 441: (AShoes, 'srb2', APriceAwesome, 3), 442: (AShoes, 'sts3', APriceBasic, 6), 443: (AShoes, 'sts4', APriceBasic, 3), 444: (AShoes, 'sts5', APriceBasic, 2), 445: (AShoes, 'srb3', APriceCool, 5), 446: (AShoes, 'srb4', APriceCool, 3), 447: (AShoes, 'sat4', APriceBasic, 3), 448: (AShoes, 'shw1', APriceCool, 7), 449: (AShoes, 'shw2', APriceCool, 7)}
15.176152
29
0.413304
ATArticle = 0 ATString = 1 ATBasePrice = 2 ATReleased = 3 ATEmblemPrices = 4 AHat = 0 AGlasses = 1 ABackpack = 2 AShoes = 3 APriceBasic = 250 APriceBasicPlus = 400 APriceCool = 800 APriceAwesome = 1500 AccessoryTypes = {101: (AHat, 'hbb1', APriceBasic, 1), 102: (AHat, 'hsf1', APriceCool, 5), 103: (AHat, 'hrb1', APriceBasic, 1), 104: (AHat, 'hsf2', APriceCool, 0), 105: (AHat, 'hsf3', APriceCool, 0), 106: (AHat, 'hrb2', APriceBasicPlus, 3), 107: (AHat, 'hrb3', APriceBasicPlus, 0), 108: (AHat, 'hht1', APriceCool, 4), 109: (AHat, 'hht2', APriceCool, 3), 110: (AHat, 'htp1', APriceCool, 3), 111: (AHat, 'htp2', APriceCool, 0), 112: (AHat, 'hav1', 3500, 0), 113: (AHat, 'hfp1', 3500, 0), 114: (AHat, 'hsg1', 3500, 0), 115: (AHat, 'hwt1', 3500, 0), 116: (AHat, 'hfz1', APriceCool, 5), 117: (AHat, 'hgf1', APriceCool, 1), 118: (AHat, 'hpt1', APriceBasicPlus, 1), 119: (AHat, 'hpb1', APriceBasicPlus, 6), 120: (AHat, 'hcr1', 10000, 5), 121: (AHat, 'hbb2', APriceBasic, 2), 122: (AHat, 'hbb3', APriceBasic, 2), 123: (AHat, 'hcw1', APriceCool, 1), 124: (AHat, 'hpr1', APriceAwesome, 1), 125: (AHat, 'hpp1', APriceBasicPlus, 1), 126: (AHat, 'hfs1', APriceCool, 1), 127: (AHat, 'hsb1', APriceAwesome, 1), 128: (AHat, 'hst1', APriceBasicPlus, 1), 129: (AHat, 'hsu1', APriceCool, 1), 130: (AHat, 'hrb4', APriceBasic, 1), 131: (AHat, 'hrb5', APriceBasicPlus, 4), 132: (AHat, 'hrb6', APriceBasic, 2), 133: (AHat, 'hrb7', APriceBasicPlus, 6), 134: (AHat, 'hat1', APriceCool, 2), 135: (AHat, 'hhd1', APriceCool, 2), 136: (AHat, 'hbw1', APriceCool, 6), 137: (AHat, 'hch1', APriceCool, 5), 138: (AHat, 'hdt1', APriceAwesome, 6), 139: (AHat, 'hft1', APriceCool, 4), 140: (AHat, 'hfd1', APriceCool, 6), 141: (AHat, 'hmk1', APriceAwesome, 2), 142: (AHat, 'hft2', APriceCool, 6), 143: (AHat, 'hhd2', APriceCool, 3), 144: (AHat, 'hpc1', APriceCool, 5), 145: (AHat, 'hrh1', APriceCool, 2), 146: (AHat, 'hhm1', 2500, 2), 147: (AHat, 'hat2', APriceCool, 2), 148: (AHat, 'htr1', 10000, 3), 149: (AHat, 'hhm2', APriceAwesome, 2), 150: (AHat, 'hwz1', APriceCool, 2), 151: (AHat, 'hwz2', APriceCool, 2), 152: (AHat, 'hhm3', APriceAwesome, 6), 153: (AHat, 'hhm4', APriceAwesome, 5), 154: (AHat, 'hfp2', APriceCool, 5), 155: (AHat, 'hhm5', APriceAwesome, 4), 156: (AHat, 'hnp1', APriceAwesome, 6), 157: (AHat, 'hpc2', APriceAwesome, 3), 158: (AHat, 'hph1', APriceAwesome, 4), 159: (AHat, 'hwg1', APriceCool, 5), 160: (AHat, 'hbb4', APriceBasic, 5), 161: (AHat, 'hbb5', APriceBasic, 2), 162: (AHat, 'hbb6', APriceBasic, 5), 163: (AHat, 'hsl1', APriceCool, 5), 164: (AHat, 'hfr1', 3000, 4), 165: (AHat, 'hby1', APriceAwesome, 5), 166: (AHat, 'hrb8', APriceBasicPlus, 6), 167: (AHat, 'hjh1', APriceAwesome, 3), 168: (AHat, 'hbb7', APriceBasic, 6), 169: (AHat, 'hrb9', APriceBasicPlus, 6), 170: (AHat, 'hwt2', APriceAwesome, 4), 171: (AHat, 'hhw1', APriceBasicPlus, 7), 172: (AHat, 'hhw2', 900, 7), 173: (AHat, 'hob1', APriceAwesome, 6), 174: (AHat, 'hbn1', APriceAwesome, 8), 175: (AHat, 'hpt2', APriceCool, 9), 176: (AHat, 'kmh1', APriceAwesome, 8), 201: (AGlasses, 'grd1', APriceBasicPlus, 0), 202: (AGlasses, 'gmb1', APriceCool, 1), 203: (AGlasses, 'gnr1', APriceCool, 0), 204: (AGlasses, 'gst1', APriceBasicPlus, 1), 205: (AGlasses, 'g3d1', APriceCool, 1), 206: (AGlasses, 'gav1', APriceCool, 1), 207: (AGlasses, 'gce1', APriceCool, 2), 208: (AGlasses, 'gdk1', APriceBasic, 1), 209: (AGlasses, 'gjo1', APriceBasicPlus, 1), 210: (AGlasses, 'gsb1', APriceAwesome, 1), 211: (AGlasses, 'ggl1', APriceCool, 6), 212: (AGlasses, 'ggm1', APriceBasicPlus, 2), 213: (AGlasses, 'ghg1', APriceAwesome, 3), 214: (AGlasses, 'gie1', APriceCool, 2), 215: (AGlasses, 'gmt1', APriceCool, 2), 216: (AGlasses, 'gmt2', APriceCool, 2), 217: (AGlasses, 'gmt3', 3500, 5), 218: (AGlasses, 'gmt4', 3500, 5), 219: (AGlasses, 'gmt5', 3500, 5), 220: (AGlasses, 'gmn1', APriceAwesome, 6), 221: (AGlasses, 'gmo1', APriceAwesome, 4), 222: (AGlasses, 'gsr1', APriceBasicPlus, 5), 223: (AGlasses, 'ghw1', APriceBasic, 0), 224: (AGlasses, 'ghw2', APriceBasic, 7), 225: (AGlasses, 'gag1', APriceAwesome, 8), 226: (AGlasses, 'ghy1', APriceAwesome, 8), 301: (ABackpack, 'bpb1', APriceBasic, 4), 302: (ABackpack, 'bpb2', APriceBasic, 1), 303: (ABackpack, 'bpb3', APriceBasic, 5), 304: (ABackpack, 'bpd1', APriceBasicPlus, 4), 305: (ABackpack, 'bpd2', APriceBasicPlus, 5), 306: (ABackpack, 'bwg1', APriceCool, 2), 307: (ABackpack, 'bwg2', APriceCool, 2), 308: (ABackpack, 'bwg3', APriceCool, 1), 309: (ABackpack, 'bst1', APriceAwesome, 1), 310: (ABackpack, 'bfn1', APriceCool, 1), 311: (ABackpack, 'baw1', APriceCool, 3), 312: (ABackpack, 'baw2', APriceAwesome, 2), 313: (ABackpack, 'bwt1', 3000, 3), 314: (ABackpack, 'bwg4', APriceAwesome, 6), 315: (ABackpack, 'bwg5', 3000, 5), 316: (ABackpack, 'bwg6', 3000, 4), 317: (ABackpack, 'bjp1', 3000, 1), 318: (ABackpack, 'blg1', APriceCool, 2), 319: (ABackpack, 'bsa1', 2500, 5), 320: (ABackpack, 'bwg7', APriceAwesome, 6), 321: (ABackpack, 'bsa2', 2000, 2), 322: (ABackpack, 'bsa3', 2000, 2), 323: (ABackpack, 'bap1', 5000, 4), 324: (ABackpack, 'bhw1', 900, 7), 325: (ABackpack, 'bhw2', APriceBasicPlus, 7), 326: (ABackpack, 'bhw3', APriceBasicPlus, 7), 327: (ABackpack, 'bhw4', 900, 7), 328: (ABackpack, 'bob1', 3000, 6), 329: (ABackpack, 'bfg1', 3000, 6), 330: (ABackpack, 'bfl1', APriceAwesome, 8), 401: (AShoes, 'sat1', APriceBasic, 3), 402: (AShoes, 'sat2', APriceBasic, 1), 403: (AShoes, 'smb1', APriceAwesome, 1), 404: (AShoes, 'scs1', APriceBasicPlus, 6), 405: (AShoes, 'swt1', APriceBasicPlus, 1), 406: (AShoes, 'smj1', APriceBasicPlus, 1), 407: (AShoes, 'sdk1', APriceBasic, 1), 408: (AShoes, 'sat3', APriceBasic, 1), 409: (AShoes, 'scs2', APriceBasicPlus, 1), 410: (AShoes, 'scs3', APriceBasicPlus, 1), 411: (AShoes, 'scs4', APriceBasicPlus, 1), 412: (AShoes, 'scb1', APriceAwesome, 1), 413: (AShoes, 'sfb1', APriceCool, 1), 414: (AShoes, 'sht1', APriceAwesome, 4), 415: (AShoes, 'smj2', APriceBasicPlus, 3), 416: (AShoes, 'smj3', APriceBasicPlus, 4), 417: (AShoes, 'ssb1', APriceAwesome, 2), 418: (AShoes, 'sts1', APriceBasic, 5), 419: (AShoes, 'sts2', APriceBasic, 4), 420: (AShoes, 'scs5', APriceBasicPlus, 4), 421: (AShoes, 'smb2', APriceAwesome, 3), 422: (AShoes, 'smb3', APriceAwesome, 2), 423: (AShoes, 'smb4', APriceAwesome, 5), 424: (AShoes, 'sfb2', 2000, 6), 425: (AShoes, 'sfb3', 2000, 4), 426: (AShoes, 'sfb4', 2000, 3), 427: (AShoes, 'sfb5', 2000, 5), 428: (AShoes, 'sfb6', 2000, 4), 429: (AShoes, 'slf1', APriceBasicPlus, 3), 430: (AShoes, 'smj4', APriceBasicPlus, 2), 431: (AShoes, 'smt1', APriceAwesome, 4), 432: (AShoes, 'sox1', APriceAwesome, 5), 433: (AShoes, 'srb1', APriceAwesome, 6), 434: (AShoes, 'sst1', 3000, 3), 435: (AShoes, 'swb1', APriceCool, 3), 436: (AShoes, 'swb2', APriceCool, 4), 437: (AShoes, 'swk1', APriceAwesome, 3), 438: (AShoes, 'scs6', APriceBasicPlus, 0), 439: (AShoes, 'smb5', APriceAwesome, 3), 440: (AShoes, 'sht2', APriceAwesome, 4), 441: (AShoes, 'srb2', APriceAwesome, 3), 442: (AShoes, 'sts3', APriceBasic, 6), 443: (AShoes, 'sts4', APriceBasic, 3), 444: (AShoes, 'sts5', APriceBasic, 2), 445: (AShoes, 'srb3', APriceCool, 5), 446: (AShoes, 'srb4', APriceCool, 3), 447: (AShoes, 'sat4', APriceBasic, 3), 448: (AShoes, 'shw1', APriceCool, 7), 449: (AShoes, 'shw2', APriceCool, 7)}
true
true
f727679b242e26a0cafd9fa4682d96dd99b90d0a
2,309
py
Python
Extra_python/Scripts/manualDel.py
JPGarCar/HORS
e06d4be00921d09f89406da5e64bbb5717c8bf07
[ "MIT" ]
1
2019-12-23T22:43:46.000Z
2019-12-23T22:43:46.000Z
Extra_python/Scripts/manualDel.py
JPGarCar/HORS
e06d4be00921d09f89406da5e64bbb5717c8bf07
[ "MIT" ]
18
2021-01-15T02:35:48.000Z
2021-12-08T17:39:51.000Z
Extra_python/Scripts/manualDel.py
JPGarCar/HORS
e06d4be00921d09f89406da5e64bbb5717c8bf07
[ "MIT" ]
null
null
null
from cs50 import SQL db = SQL("sqlite:///immuns.db") global currentUser def manualDel(number, curUser): stem = db.execute("SELECT * FROM :dataBase WHERE id=:ids", dataBase=curUser, ids=number) for stoop in stem: comm = stoop["committee"] db.execute("UPDATE generalList SET delegate_name = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("UPDATE generalList SET delegate_school = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) if comm[-2:] == "MS": db.execute("UPDATE msen SET delegate_name = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("UPDATE mssp SET delegate_name = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("UPDATE msen SET delegate_school = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("UPDATE mssp SET delegate_school = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) elif comm[-2:] == "HS": db.execute("UPDATE hsen SET delegate_name = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("UPDATE hssp SET delegate_name = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("UPDATE hsen SET delegate_school = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("UPDATE hssp SET delegate_school = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) else: db.execute("UPDATE hsen SET delegate_name = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("UPDATE hsen SET delegate_school = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("DELETE FROM :dataBase WHERE id=:ids", dataBase=curUser, ids=number) currentUser = "GuillermoLopezIndividualGuillermo" numberList = [1] for number in numberList: manualDel(number, currentUser)
69.969697
149
0.672152
from cs50 import SQL db = SQL("sqlite:///immuns.db") global currentUser def manualDel(number, curUser): stem = db.execute("SELECT * FROM :dataBase WHERE id=:ids", dataBase=curUser, ids=number) for stoop in stem: comm = stoop["committee"] db.execute("UPDATE generalList SET delegate_name = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("UPDATE generalList SET delegate_school = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) if comm[-2:] == "MS": db.execute("UPDATE msen SET delegate_name = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("UPDATE mssp SET delegate_name = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("UPDATE msen SET delegate_school = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("UPDATE mssp SET delegate_school = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) elif comm[-2:] == "HS": db.execute("UPDATE hsen SET delegate_name = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("UPDATE hssp SET delegate_name = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("UPDATE hsen SET delegate_school = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("UPDATE hssp SET delegate_school = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) else: db.execute("UPDATE hsen SET delegate_name = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("UPDATE hsen SET delegate_school = '' WHERE committee=:com AND country=:con", com=stoop["committee"] ,con=stoop["country"]) db.execute("DELETE FROM :dataBase WHERE id=:ids", dataBase=curUser, ids=number) currentUser = "GuillermoLopezIndividualGuillermo" numberList = [1] for number in numberList: manualDel(number, currentUser)
true
true
f72767e3fe7d8c9e8e9895a0ec1f3c6a2f6fe9d2
1,765
py
Python
products/migrations/0001_initial.py
UB-ES-2021-A1/wannasell-backend
84360b2985fc28971867601373697f39303e396b
[ "Unlicense" ]
null
null
null
products/migrations/0001_initial.py
UB-ES-2021-A1/wannasell-backend
84360b2985fc28971867601373697f39303e396b
[ "Unlicense" ]
62
2021-11-22T21:52:44.000Z
2021-12-17T15:07:02.000Z
products/migrations/0001_initial.py
UB-ES-2021-A1/wannasell-backend
84360b2985fc28971867601373697f39303e396b
[ "Unlicense" ]
null
null
null
# Generated by Django 3.2.8 on 2021-10-18 11:53 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Product', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.TextField(max_length=500)), ('description', models.TextField(blank=True, max_length=1000)), ('price', models.DecimalField(decimal_places=2, max_digits=6)), ('category', models.CharField(choices=[('CO', 'Coches'), ('MO', 'Motos'), ('MA', 'Moda y Accesorios'), ('IM', 'Immobiliaria'), ('TV', 'TV, Audio y Foto'), ('TE', 'Móviles y Telefonía'), ('IE', 'Informática y Electrónica'), ('DO', 'Deporte y Ocio'), ('BI', 'Bicicletas'), ('CV', 'Consolas y Videojuegos'), ('HJ', 'Hogar y Jardín'), ('ED', 'Electrodomésticos'), ('CU', 'Cine, Libros y Música'), ('NI', 'Niños y Bebés'), ('CC', 'Coleccionismo'), ('CT', 'Construcción y reformas'), ('IN', 'Industria y Agricultura'), ('EM', 'Empleo'), ('SE', 'Servicios'), ('OT', 'Otros')], default='OT', max_length=2)), ], ), migrations.CreateModel( name='Image', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.ImageField(blank=True, upload_to='products/%Y/%m/%d')), ('product', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, related_name='images', to='products.product')), ], ), ]
51.911765
615
0.586969
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Product', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.TextField(max_length=500)), ('description', models.TextField(blank=True, max_length=1000)), ('price', models.DecimalField(decimal_places=2, max_digits=6)), ('category', models.CharField(choices=[('CO', 'Coches'), ('MO', 'Motos'), ('MA', 'Moda y Accesorios'), ('IM', 'Immobiliaria'), ('TV', 'TV, Audio y Foto'), ('TE', 'Móviles y Telefonía'), ('IE', 'Informática y Electrónica'), ('DO', 'Deporte y Ocio'), ('BI', 'Bicicletas'), ('CV', 'Consolas y Videojuegos'), ('HJ', 'Hogar y Jardín'), ('ED', 'Electrodomésticos'), ('CU', 'Cine, Libros y Música'), ('NI', 'Niños y Bebés'), ('CC', 'Coleccionismo'), ('CT', 'Construcción y reformas'), ('IN', 'Industria y Agricultura'), ('EM', 'Empleo'), ('SE', 'Servicios'), ('OT', 'Otros')], default='OT', max_length=2)), ], ), migrations.CreateModel( name='Image', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.ImageField(blank=True, upload_to='products/%Y/%m/%d')), ('product', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, related_name='images', to='products.product')), ], ), ]
true
true
f727686cecf1ae4d8cd0131fdaf4bd65fedf922c
8,921
py
Python
python_samples/Python_Examples/ibm_db/ibm_db-special_columns.py
adrianmahjour/db2-samples
ff984aec81c5c08ce28443d896c0818cfae4f789
[ "Apache-2.0" ]
54
2019-08-02T13:15:07.000Z
2022-03-21T17:36:48.000Z
python_samples/Python_Examples/ibm_db/ibm_db-special_columns.py
junsulee75/db2-samples
d9ee03101cad1f9167eebc1609b4151559124017
[ "Apache-2.0" ]
13
2019-07-26T13:51:16.000Z
2022-03-25T21:43:52.000Z
python_samples/Python_Examples/ibm_db/ibm_db-special_columns.py
junsulee75/db2-samples
d9ee03101cad1f9167eebc1609b4151559124017
[ "Apache-2.0" ]
75
2019-07-20T04:53:24.000Z
2022-03-23T20:56:55.000Z
#! /usr/bin/python3 #-------------------------------------------------------------------------------------------------# # NAME: ibm_db-special_columns.py # # # # PURPOSE: This program is designed to illustrate how to use the ibm_db.special_columns() API. # # # # Additional APIs used: # # ibm_db.fetch_assoc() # # # # USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # # following command from a terminal window: # # # # ./ibm_db-special_columns.py # # # #-------------------------------------------------------------------------------------------------# # DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # # # # (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # # Licensed Materials - Property of IBM # # # # US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # # Schedule Contract with IBM Corp. # # # # The following source code ("Sample") is owned by International Business Machines Corporation # # or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # # copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # # of assisting you in the creation of Python applications using the ibm_db library. # # # # The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # # HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # # Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # # above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # # you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # # has been advised of the possibility of such damages. # #-------------------------------------------------------------------------------------------------# # Load The Appropriate Python Modules import sys # Provides Information About Python Interpreter Constants, Functions, & Methods import ibm_db # Contains The APIs Needed To Work With Db2 Databases #-------------------------------------------------------------------------------------------------# # Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # # In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # # Establish And Terminate A Connection To A Db2 Server Or Database # #-------------------------------------------------------------------------------------------------# from ibm_db_tools import Db2ConnectionMgr #-------------------------------------------------------------------------------------------------# # Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # # File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # # Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # # Invoked In A Jupyter Notebook # #-------------------------------------------------------------------------------------------------# from ipynb_exit import exit # Define And Initialize The Appropriate Variables dbName = "SAMPLE" userID = "db2inst1" passWord = "Passw0rd" dbConnection = None schemaName = userID.upper() tableName = "EMPLOYEE" resultSet = False dataRecord = False sqlDataTypes = {0 : "SQL_UNKNOWN_TYPE", 1 : "SQL_CHAR", 2 : "SQL_NUMERIC", 3 : "SQL_DECIMAL", 4 : "SQL_INTEGER", 5 : "SQL_SMALLINT", 6 : "SQL_FLOAT", 7 : "SQL_REAL", 8 : "SQL_DOUBLE", 9 : "SQL_DATETIME", 12 : "SQL_VARCHAR", 16 : "SQL_BOOLEAN", 19 : "SQL_ROW", 91 : "SQL_TYPE_DATE", 92 : "SQL_TYPE_TIME", 93 : "SQL_TYPE_TIMESTAMP", 95 : "SQL_TYPE_TIMESTAMP_WITH_TIMEZONE", -8 : "SQL_WCHAR", -9 : "SQL_WVARCHAR", -10 : "SQL_WLONGVARCHAR", -95 : "SQL_GRAPHIC", -96 : "SQL_VARGRAPHIC", -97 : "SQL_LONGVARGRAPHIC", -98 : "SQL_BLOB", -99 : "SQL_CLOB", -350 : "SQL_DBCLOB", -360 : "SQL_DECFLOAT", -370 : "SQL_XML", -380 : "SQL_CURSORHANDLE", -400 : "SQL_DATALINK", -450 : "SQL_USER_DEFINED_TYPE"} # Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) conn.openConnection() if conn.returnCode is True: dbConnection = conn.connectionID else: conn.closeConnection() exit(-1) # Attempt To Retrieve Information About Unique Row Identifier Columns That Have Been # Defined For The Table Specified print("Obtaining information about unique row identifier columns that have been") print("defined for the " + schemaName + "." + tableName + " table ... ", end="") try: resultSet = ibm_db.special_columns(dbConnection, None, schemaName, tableName, 0) except Exception: pass # If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit if resultSet is False: print("\nERROR: Unable to obtain the information desired\n.") conn.closeConnection() exit(-1) # Otherwise, Complete The Status Message else: print("Done!\n") # As Long As There Are Records (That Were Produced By The ibm_db.special_columns API), ... noData = False loopCounter = 1 while noData is False: # Retrieve A Record And Store It In A Python Dictionary try: dataRecord = ibm_db.fetch_assoc(resultSet) except: pass # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The # "No Data" Flag And Exit The Loop if dataRecord is False: noData = True # Otherwise, Display The Information Retrieved else: # Display Record Header Information print("Primary key/unique index " + str(loopCounter) + " details:") print("___________________________________") # Display The Information Stored In The Data Record Retrieved print("Column name : {}" .format(dataRecord['COLUMN_NAME'])) print("Data type : {}" .format(dataRecord['TYPE_NAME'])) print("SQL data type : ", end="") print(sqlDataTypes.get(dataRecord['DATA_TYPE'])) print("Column size : {}" .format(dataRecord['COLUMN_SIZE'])) print("Buffer size : {}" .format(dataRecord['BUFFER_LENGTH'])) print("Scale (decimal digits) : {}" .format(dataRecord['DECIMAL_DIGITS'])) print("Scope : ", end="") if dataRecord['SCOPE'] == 0: print("Row ID is valid only while the\n" + " " * 25, end="") print("cursor is positioned on the row") elif dataRecord['SCOPE'] == 1: print("Row ID is valid for the\n" + " " * 25, end="") print("duration of the transaction") elif dataRecord['SCOPE'] == 2: print("Row ID is valid for the\n" + " " * 25, end="") print("duration of the connection") # Increment The loopCounter Variable And Print A Blank Line To Separate The # Records From Each Other loopCounter += 1 print() # Close The Database Connection That Was Opened Earlier conn.closeConnection() # Return Control To The Operating System exit()
56.462025
99
0.512723
import sys import ibm_db from ibm_db_tools import Db2ConnectionMgr from ipynb_exit import exit dbName = "SAMPLE" userID = "db2inst1" passWord = "Passw0rd" dbConnection = None schemaName = userID.upper() tableName = "EMPLOYEE" resultSet = False dataRecord = False sqlDataTypes = {0 : "SQL_UNKNOWN_TYPE", 1 : "SQL_CHAR", 2 : "SQL_NUMERIC", 3 : "SQL_DECIMAL", 4 : "SQL_INTEGER", 5 : "SQL_SMALLINT", 6 : "SQL_FLOAT", 7 : "SQL_REAL", 8 : "SQL_DOUBLE", 9 : "SQL_DATETIME", 12 : "SQL_VARCHAR", 16 : "SQL_BOOLEAN", 19 : "SQL_ROW", 91 : "SQL_TYPE_DATE", 92 : "SQL_TYPE_TIME", 93 : "SQL_TYPE_TIMESTAMP", 95 : "SQL_TYPE_TIMESTAMP_WITH_TIMEZONE", -8 : "SQL_WCHAR", -9 : "SQL_WVARCHAR", -10 : "SQL_WLONGVARCHAR", -95 : "SQL_GRAPHIC", -96 : "SQL_VARGRAPHIC", -97 : "SQL_LONGVARGRAPHIC", -98 : "SQL_BLOB", -99 : "SQL_CLOB", -350 : "SQL_DBCLOB", -360 : "SQL_DECFLOAT", -370 : "SQL_XML", -380 : "SQL_CURSORHANDLE", -400 : "SQL_DATALINK", -450 : "SQL_USER_DEFINED_TYPE"} conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) conn.openConnection() if conn.returnCode is True: dbConnection = conn.connectionID else: conn.closeConnection() exit(-1) print("Obtaining information about unique row identifier columns that have been") print("defined for the " + schemaName + "." + tableName + " table ... ", end="") try: resultSet = ibm_db.special_columns(dbConnection, None, schemaName, tableName, 0) except Exception: pass if resultSet is False: print("\nERROR: Unable to obtain the information desired\n.") conn.closeConnection() exit(-1) else: print("Done!\n") noData = False loopCounter = 1 while noData is False: try: dataRecord = ibm_db.fetch_assoc(resultSet) except: pass if dataRecord is False: noData = True else: print("Primary key/unique index " + str(loopCounter) + " details:") print("___________________________________") print("Column name : {}" .format(dataRecord['COLUMN_NAME'])) print("Data type : {}" .format(dataRecord['TYPE_NAME'])) print("SQL data type : ", end="") print(sqlDataTypes.get(dataRecord['DATA_TYPE'])) print("Column size : {}" .format(dataRecord['COLUMN_SIZE'])) print("Buffer size : {}" .format(dataRecord['BUFFER_LENGTH'])) print("Scale (decimal digits) : {}" .format(dataRecord['DECIMAL_DIGITS'])) print("Scope : ", end="") if dataRecord['SCOPE'] == 0: print("Row ID is valid only while the\n" + " " * 25, end="") print("cursor is positioned on the row") elif dataRecord['SCOPE'] == 1: print("Row ID is valid for the\n" + " " * 25, end="") print("duration of the transaction") elif dataRecord['SCOPE'] == 2: print("Row ID is valid for the\n" + " " * 25, end="") print("duration of the connection") loopCounter += 1 print() conn.closeConnection() exit()
true
true
f72768f88bd6b9a784e985befa28896108619edb
3,690
py
Python
tests/integration/test_unsteady_ring_vortex_lattice_method_static_geometry.py
KamiGazi/PteraSoftware
3b6f6bfb8db776970674234cb524c338ecc82df1
[ "MIT" ]
null
null
null
tests/integration/test_unsteady_ring_vortex_lattice_method_static_geometry.py
KamiGazi/PteraSoftware
3b6f6bfb8db776970674234cb524c338ecc82df1
[ "MIT" ]
null
null
null
tests/integration/test_unsteady_ring_vortex_lattice_method_static_geometry.py
KamiGazi/PteraSoftware
3b6f6bfb8db776970674234cb524c338ecc82df1
[ "MIT" ]
null
null
null
"""This is a testing case for the unsteady ring vortex lattice method solver with static geometry. Based on an equivalent XFLR5 testing case, the expected output for this case is: CL: 0.588 CDi: 0.011 Cm: -0.197 Note: The expected output was created using XFLR5's inviscid VLM2 analysis type, which is a ring vortex lattice method solver. The geometry in this case is static. Therefore the results of this unsteady solver should converge to be close to XFLR5's static result. This module contains the following classes: TestUnsteadyRingVortexLatticeMethodStaticGeometry: This is a class for testing the unsteady ring vortex lattice method solver on static geometry. This module contains the following exceptions: None This module contains the following functions: None """ import unittest import pterasoftware as ps from tests.integration.fixtures import solver_fixtures class TestUnsteadyRingVortexLatticeMethodStaticGeometry(unittest.TestCase): """This is a class for testing the unsteady ring vortex lattice method solver on static geometry. This class contains the following public methods: setUp: This method sets up the test. tearDown: This method tears down the test. test_method: This method tests the solver's output. This class contains the following class attributes: None Subclassing: This class is not meant to be subclassed. """ def setUp(self): """This method sets up the test. :return: None """ # Create the unsteady method solver. self.unsteady_ring_vortex_lattice_method_validation_solver = ( solver_fixtures.make_unsteady_ring_vortex_lattice_method_validation_solver_with_static_geometry() ) def tearDown(self): """This method tears down the test. :return: None """ del self.unsteady_ring_vortex_lattice_method_validation_solver def test_method(self): """This method tests the solver's output. :return: None """ # Run the solver. self.unsteady_ring_vortex_lattice_method_validation_solver.run( prescribed_wake=True ) this_solver = self.unsteady_ring_vortex_lattice_method_validation_solver this_airplane = this_solver.current_airplanes[0] # Calculate the percent errors of the output. c_di_expected = 0.011 c_di_calculated = this_airplane.total_near_field_force_coefficients_wind_axes[0] c_di_error = abs(c_di_calculated - c_di_expected) / c_di_expected c_l_expected = 0.588 c_l_calculated = this_airplane.total_near_field_force_coefficients_wind_axes[2] c_l_error = abs(c_l_calculated - c_l_expected) / c_l_expected c_m_expected = -0.197 c_m_calculated = this_airplane.total_near_field_moment_coefficients_wind_axes[1] c_m_error = abs(c_m_calculated - c_m_expected) / c_m_expected # Set the allowable percent error. allowable_error = 0.10 ps.output.animate( unsteady_solver=self.unsteady_ring_vortex_lattice_method_validation_solver, show_wake_vortices=True, show_delta_pressures=True, keep_file=False, ) ps.output.plot_results_versus_time( unsteady_solver=self.unsteady_ring_vortex_lattice_method_validation_solver ) # Assert that the percent errors are less than the allowable error. self.assertTrue(abs(c_di_error) < allowable_error) self.assertTrue(abs(c_l_error) < allowable_error) self.assertTrue(abs(c_m_error) < allowable_error)
32.946429
109
0.712737
import unittest import pterasoftware as ps from tests.integration.fixtures import solver_fixtures class TestUnsteadyRingVortexLatticeMethodStaticGeometry(unittest.TestCase): def setUp(self): self.unsteady_ring_vortex_lattice_method_validation_solver = ( solver_fixtures.make_unsteady_ring_vortex_lattice_method_validation_solver_with_static_geometry() ) def tearDown(self): del self.unsteady_ring_vortex_lattice_method_validation_solver def test_method(self): self.unsteady_ring_vortex_lattice_method_validation_solver.run( prescribed_wake=True ) this_solver = self.unsteady_ring_vortex_lattice_method_validation_solver this_airplane = this_solver.current_airplanes[0] c_di_expected = 0.011 c_di_calculated = this_airplane.total_near_field_force_coefficients_wind_axes[0] c_di_error = abs(c_di_calculated - c_di_expected) / c_di_expected c_l_expected = 0.588 c_l_calculated = this_airplane.total_near_field_force_coefficients_wind_axes[2] c_l_error = abs(c_l_calculated - c_l_expected) / c_l_expected c_m_expected = -0.197 c_m_calculated = this_airplane.total_near_field_moment_coefficients_wind_axes[1] c_m_error = abs(c_m_calculated - c_m_expected) / c_m_expected allowable_error = 0.10 ps.output.animate( unsteady_solver=self.unsteady_ring_vortex_lattice_method_validation_solver, show_wake_vortices=True, show_delta_pressures=True, keep_file=False, ) ps.output.plot_results_versus_time( unsteady_solver=self.unsteady_ring_vortex_lattice_method_validation_solver ) self.assertTrue(abs(c_di_error) < allowable_error) self.assertTrue(abs(c_l_error) < allowable_error) self.assertTrue(abs(c_m_error) < allowable_error)
true
true
f7276a118dd544956c6a75767571b4963130bb32
192
py
Python
setup.py
ericlee0803/lookahead_release
373295f11be81d82b1c69eeadeec32ae96f26b1f
[ "MIT" ]
3
2020-06-17T20:25:12.000Z
2020-11-24T17:21:59.000Z
setup.py
ericlee0803/lookahead_release
373295f11be81d82b1c69eeadeec32ae96f26b1f
[ "MIT" ]
null
null
null
setup.py
ericlee0803/lookahead_release
373295f11be81d82b1c69eeadeec32ae96f26b1f
[ "MIT" ]
null
null
null
from setuptools import setup, find_packages setup( name='lookahead', version='0.0.2', packages=find_packages(), install_requires=['scikit-learn', 'scipy', 'numpy', 'qmcpy'] )
21.333333
64
0.671875
from setuptools import setup, find_packages setup( name='lookahead', version='0.0.2', packages=find_packages(), install_requires=['scikit-learn', 'scipy', 'numpy', 'qmcpy'] )
true
true
f7276a2c611535e6562f2d0b10dcd978082fd085
10,047
py
Python
gabriel/server/gabriel3/proxy/common.py
lee4138/6d-pose-estimation-with-ml-in-ar
e29162c82c867d4a8177322d7d49a55c5fd90639
[ "MIT" ]
7
2020-02-04T10:58:58.000Z
2021-11-26T07:37:22.000Z
gabriel/server/gabriel3/proxy/common.py
buaafw/6d-pose-estimation-with-ml-in-ar
e29162c82c867d4a8177322d7d49a55c5fd90639
[ "MIT" ]
1
2021-02-19T03:56:10.000Z
2021-02-19T03:56:10.000Z
gabriel/server/gabriel3/proxy/common.py
buaafw/6d-pose-estimation-with-ml-in-ar
e29162c82c867d4a8177322d7d49a55c5fd90639
[ "MIT" ]
8
2019-12-05T10:05:36.000Z
2021-01-27T14:09:53.000Z
#!/usr/bin/env python # # Cloudlet Infrastructure for Mobile Computing # # Author: Kiryong Ha <krha@cmu.edu> # Zhuo Chen <zhuoc@cs.cmu.edu> # # Copyright (C) 2011-2013 Carnegie Mellon University # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import json import multiprocessing import queue import select import socket import struct import sys import threading import time import traceback import gabriel3 LOG = gabriel3.logging.getLogger(__name__) class ProxyError(Exception): pass class SensorReceiveClient(gabriel3.network.CommonClient): """ This client will receive data from the control server as much as possible. And put the data into the @output_queue, so that the other thread (@CognitiveProcessThread) can use the data """ def __init__(self, control_addr, output_queue): gabriel3.network.CommonClient.__init__(self, control_addr) self.output_queue = output_queue def __repr__(self): return "Sensor Receive Client" def _handle_input_data(self): # receive data from control VM header_size = struct.unpack("!I", self._recv_all(4))[0] data_size = struct.unpack("!I", self._recv_all(4))[0] header_str = self._recv_all(header_size) data = self._recv_all(data_size) header_json = json.loads(header_str) # add header data for measurement if gabriel3.Debug.TIME_MEASUREMENT: header_json[gabriel3.Protocol_measurement.JSON_KEY_APP_RECV_TIME] = time.time() # token buffer - discard if the token(queue) is not available if self.output_queue.full(): try: self.output_queue.get_nowait() except queue.Empty as e: pass self.output_queue.put((header_json, data)) class CognitiveProcessThread(threading.Thread): ''' The thread that does real processing. It takes input data from @data_queue and puts output data into @output_queue. An interesting cognitive engine should implement its own @handle function. ''' def __init__(self, data_queue, output_queue, engine_id = None): self.data_queue = data_queue self.output_queue = output_queue self.engine_id = engine_id self.stop = threading.Event() threading.Thread.__init__(self, target = self.run) def __repr__(self): return "Cognitive Processing Thread" def run(self): while(not self.stop.wait(0.0001)): try: (header, data) = self.data_queue.get(timeout = 0.0001) if header is None or data is None: LOG.warning("header or data in data_queue is not valid!") continue except queue.Empty as e: continue ## the real processing # header can be changed directly in the proxy (design choice made for backward compatibility) result = self.handle(header, data) # header is in JSON format if result is None: # A special return that marks the result useless continue ## put return data into output queue rtn_json = header rtn_json[gabriel3.Protocol_client.JSON_KEY_ENGINE_ID] = self.engine_id if gabriel3.Debug.TIME_MEASUREMENT: rtn_json[gabriel3.Protocol_measurement.JSON_KEY_APP_SENT_TIME] = time.time() self.output_queue.put( (json.dumps(rtn_json), result) ) LOG.info("[TERMINATE] Finish %s" % str(self)) def handle(self, header, data): # header is in JSON format return None def terminate(self): self.stop.set() class MasterProxyThread(threading.Thread): ''' The thread that distributes data to multiple worker threads. Similar to @CognitiveProcessThread, it takes input data from @data_queue. However, is should implement its own @handle function to decide where the data goes. ''' def __init__(self, data_queue, engine_id = None): self.data_queue = data_queue self.engine_id = engine_id self.stop = threading.Event() threading.Thread.__init__(self, target = self.run) def __repr__(self): return "Cognitive Processing Thread" def run(self): while(not self.stop.wait(0.0001)): try: (header, data) = self.data_queue.get(timeout = 0.0001) if header is None or data is None: LOG.warning("header or data in data_queue is not valid!") continue except queue.Empty as e: continue ## the real processing self.handle(header, data) # header is in JSON format LOG.info("[TERMINATE] Finish %s" % str(self)) def handle(self, header, data): # header is in JSON format pass def terminate(self): self.stop.set() class ResultPublishClient(gabriel3.network.CommonClient): """ This client will publish processed result from @data_queue to the ucomm server. """ def __init__(self, ucomm_addr, data_queue, log_flag = True): gabriel3.network.CommonClient.__init__(self, ucomm_addr) self.data_queue = data_queue if not log_flag: import logging LOG.setLevel(logging.CRITICAL + 1) def __repr__(self): return "Result Publish Client" def _handle_queue_data(self): try: rtn_header, rtn_data = self.data_queue.get(timeout = 0.0001) total_size = len(rtn_header) + len(rtn_data) # packet format: total size, header size, header, data packet = struct.pack("!II{}s{}s".format(len(rtn_header), len(rtn_data)), total_size, len(rtn_header), str.encode(rtn_header), str.encode(rtn_data)) self.sock.sendall(packet) LOG.info("sending result to ucomm: %s" % gabriel3.util.print_rtn(json.loads(rtn_header))) except queue.Empty as e: pass class DataPublishHandler(gabriel3.network.CommonHandler): def setup(self): LOG.info("New receiver connected to data stream") super(DataPublishHandler, self).setup() self.data_queue = multiprocessing.Queue(gabriel3.Const.MAX_FRAME_SIZE) # receive engine name data_size = struct.unpack("!I", self._recv_all(4))[0] self.engine_id = self._recv_all(data_size) LOG.info("Got engine name: %s" % self.engine_id) self.engine_number = self._register_engine(self.data_queue, self.engine_id) # send engine sequence number back packet = struct.pack("!I", self.engine_number) self.request.send(packet) self.wfile.flush() def __repr__(self): return "Data Publish Server" def _handle_queue_data(self): try: (header, data) = self.data_queue.get(timeout = 0.0001) header_str = json.dumps(header) # send data packet = struct.pack("!II%ds%ds" % (len(header_str), len(data)), len(header_str), len(data), header_str, data) self.request.send(packet) self.wfile.flush() # receive result header_size = struct.unpack("!I", self._recv_all(4))[0] header_str = self._recv_all(header_size) header = json.loads(header_str) state_size = struct.unpack("!I", self._recv_all(4))[0] state = self._recv_all(state_size) header[gabriel3.Protocol_client.JSON_KEY_ENGINE_ID] = self.engine_id header[gabriel3.Protocol_client.JSON_KEY_ENGINE_NUMBER] = self.engine_number try: self.server.output_queue.put_nowait( (header, state) ) except queue.Full as e: LOG.error("%s: output queue shouldn't be full" % self) except queue.Empty as e: pass def _register_engine(self, queue, engine_id): ''' Registers the new engine. The data server will publish data to only one engine with the same @engine_id. Returns the seq number of current engine among all engines that share the same @engine_id. ''' engine_info = self.server.queue_dict.get(engine_id, None) if engine_info is None: self.server.queue_dict[engine_id] = {'queues': [queue], 'tokens': [1]} return 0 else: engine_info['queues'].append(queue) engine_info['tokens'].append(1) return len(engine_info['queues']) - 1 def _unregister_engine(self, queue, engine_id): #TODO pass def terminate(self): LOG.info("Offloading engine disconnected from video stream") self._unregister_engine(self.data_queue, engine_id) super(DataPublishHandler, self).terminate() class DataPublishServer(gabriel3.network.CommonServer): def __init__(self, port, handler, queue_dict, output_queue): gabriel3.network.CommonServer.__init__(self, port, handler) # cannot use super because it's old style class LOG.info("* Data publish server(%s) configuration" % str(self.handler)) LOG.info(" - Open TCP Server at %s" % (str(self.server_address))) LOG.info(" - Disable nagle (No TCP delay) : %s" % str(self.socket.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY))) LOG.info("-" * 50) self.queue_dict = queue_dict self.output_queue = output_queue def terminate(self): gabriel3.network.CommonServer.terminate(self)
36.270758
159
0.643973
import json import multiprocessing import queue import select import socket import struct import sys import threading import time import traceback import gabriel3 LOG = gabriel3.logging.getLogger(__name__) class ProxyError(Exception): pass class SensorReceiveClient(gabriel3.network.CommonClient): def __init__(self, control_addr, output_queue): gabriel3.network.CommonClient.__init__(self, control_addr) self.output_queue = output_queue def __repr__(self): return "Sensor Receive Client" def _handle_input_data(self): header_size = struct.unpack("!I", self._recv_all(4))[0] data_size = struct.unpack("!I", self._recv_all(4))[0] header_str = self._recv_all(header_size) data = self._recv_all(data_size) header_json = json.loads(header_str) if gabriel3.Debug.TIME_MEASUREMENT: header_json[gabriel3.Protocol_measurement.JSON_KEY_APP_RECV_TIME] = time.time() if self.output_queue.full(): try: self.output_queue.get_nowait() except queue.Empty as e: pass self.output_queue.put((header_json, data)) class CognitiveProcessThread(threading.Thread): def __init__(self, data_queue, output_queue, engine_id = None): self.data_queue = data_queue self.output_queue = output_queue self.engine_id = engine_id self.stop = threading.Event() threading.Thread.__init__(self, target = self.run) def __repr__(self): return "Cognitive Processing Thread" def run(self): while(not self.stop.wait(0.0001)): try: (header, data) = self.data_queue.get(timeout = 0.0001) if header is None or data is None: LOG.warning("header or data in data_queue is not valid!") continue except queue.Empty as e: continue result = self.handle(header, data) if result is None: continue rtn_json[gabriel3.Protocol_client.JSON_KEY_ENGINE_ID] = self.engine_id if gabriel3.Debug.TIME_MEASUREMENT: rtn_json[gabriel3.Protocol_measurement.JSON_KEY_APP_SENT_TIME] = time.time() self.output_queue.put( (json.dumps(rtn_json), result) ) LOG.info("[TERMINATE] Finish %s" % str(self)) def handle(self, header, data): return None def terminate(self): self.stop.set() class MasterProxyThread(threading.Thread): def __init__(self, data_queue, engine_id = None): self.data_queue = data_queue self.engine_id = engine_id self.stop = threading.Event() threading.Thread.__init__(self, target = self.run) def __repr__(self): return "Cognitive Processing Thread" def run(self): while(not self.stop.wait(0.0001)): try: (header, data) = self.data_queue.get(timeout = 0.0001) if header is None or data is None: LOG.warning("header or data in data_queue is not valid!") continue except queue.Empty as e: continue dle(header, data) LOG.info("[TERMINATE] Finish %s" % str(self)) def handle(self, header, data): pass def terminate(self): self.stop.set() class ResultPublishClient(gabriel3.network.CommonClient): def __init__(self, ucomm_addr, data_queue, log_flag = True): gabriel3.network.CommonClient.__init__(self, ucomm_addr) self.data_queue = data_queue if not log_flag: import logging LOG.setLevel(logging.CRITICAL + 1) def __repr__(self): return "Result Publish Client" def _handle_queue_data(self): try: rtn_header, rtn_data = self.data_queue.get(timeout = 0.0001) total_size = len(rtn_header) + len(rtn_data) packet = struct.pack("!II{}s{}s".format(len(rtn_header), len(rtn_data)), total_size, len(rtn_header), str.encode(rtn_header), str.encode(rtn_data)) self.sock.sendall(packet) LOG.info("sending result to ucomm: %s" % gabriel3.util.print_rtn(json.loads(rtn_header))) except queue.Empty as e: pass class DataPublishHandler(gabriel3.network.CommonHandler): def setup(self): LOG.info("New receiver connected to data stream") super(DataPublishHandler, self).setup() self.data_queue = multiprocessing.Queue(gabriel3.Const.MAX_FRAME_SIZE) data_size = struct.unpack("!I", self._recv_all(4))[0] self.engine_id = self._recv_all(data_size) LOG.info("Got engine name: %s" % self.engine_id) self.engine_number = self._register_engine(self.data_queue, self.engine_id) packet = struct.pack("!I", self.engine_number) self.request.send(packet) self.wfile.flush() def __repr__(self): return "Data Publish Server" def _handle_queue_data(self): try: (header, data) = self.data_queue.get(timeout = 0.0001) header_str = json.dumps(header) packet = struct.pack("!II%ds%ds" % (len(header_str), len(data)), len(header_str), len(data), header_str, data) self.request.send(packet) self.wfile.flush() header_size = struct.unpack("!I", self._recv_all(4))[0] header_str = self._recv_all(header_size) header = json.loads(header_str) state_size = struct.unpack("!I", self._recv_all(4))[0] state = self._recv_all(state_size) header[gabriel3.Protocol_client.JSON_KEY_ENGINE_ID] = self.engine_id header[gabriel3.Protocol_client.JSON_KEY_ENGINE_NUMBER] = self.engine_number try: self.server.output_queue.put_nowait( (header, state) ) except queue.Full as e: LOG.error("%s: output queue shouldn't be full" % self) except queue.Empty as e: pass def _register_engine(self, queue, engine_id): engine_info = self.server.queue_dict.get(engine_id, None) if engine_info is None: self.server.queue_dict[engine_id] = {'queues': [queue], 'tokens': [1]} return 0 else: engine_info['queues'].append(queue) engine_info['tokens'].append(1) return len(engine_info['queues']) - 1 def _unregister_engine(self, queue, engine_id): #TODO pass def terminate(self): LOG.info("Offloading engine disconnected from video stream") self._unregister_engine(self.data_queue, engine_id) super(DataPublishHandler, self).terminate() class DataPublishServer(gabriel3.network.CommonServer): def __init__(self, port, handler, queue_dict, output_queue): gabriel3.network.CommonServer.__init__(self, port, handler) # cannot use super because it's old style class LOG.info("* Data publish server(%s) configuration" % str(self.handler)) LOG.info(" - Open TCP Server at %s" % (str(self.server_address))) LOG.info(" - Disable nagle (No TCP delay) : %s" % str(self.socket.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY))) LOG.info("-" * 50) self.queue_dict = queue_dict self.output_queue = output_queue def terminate(self): gabriel3.network.CommonServer.terminate(self)
true
true
f7276a69899ad99ba6680fb0b931907cb13b39e3
2,402
py
Python
src/wormhole/test/dilate/test_parse.py
dmgolembiowski/magic-wormhole
d517a10282d5e56f300db462b1a6eec517202af7
[ "MIT" ]
2,801
2021-01-10T16:37:14.000Z
2022-03-31T19:02:50.000Z
src/wormhole/test/dilate/test_parse.py
dmgolembiowski/magic-wormhole
d517a10282d5e56f300db462b1a6eec517202af7
[ "MIT" ]
52
2021-01-10T01:54:00.000Z
2022-03-11T13:12:41.000Z
src/wormhole/test/dilate/test_parse.py
dmgolembiowski/magic-wormhole
d517a10282d5e56f300db462b1a6eec517202af7
[ "MIT" ]
106
2021-01-21T14:32:22.000Z
2022-03-18T10:33:09.000Z
from __future__ import print_function, unicode_literals import mock from twisted.trial import unittest from ..._dilation.connection import (parse_record, encode_record, KCM, Ping, Pong, Open, Data, Close, Ack) class Parse(unittest.TestCase): def test_parse(self): self.assertEqual(parse_record(b"\x00"), KCM()) self.assertEqual(parse_record(b"\x01\x55\x44\x33\x22"), Ping(ping_id=b"\x55\x44\x33\x22")) self.assertEqual(parse_record(b"\x02\x55\x44\x33\x22"), Pong(ping_id=b"\x55\x44\x33\x22")) self.assertEqual(parse_record(b"\x03\x00\x00\x02\x01\x00\x00\x01\x00"), Open(scid=513, seqnum=256)) self.assertEqual(parse_record(b"\x04\x00\x00\x02\x02\x00\x00\x01\x01dataaa"), Data(scid=514, seqnum=257, data=b"dataaa")) self.assertEqual(parse_record(b"\x05\x00\x00\x02\x03\x00\x00\x01\x02"), Close(scid=515, seqnum=258)) self.assertEqual(parse_record(b"\x06\x00\x00\x01\x03"), Ack(resp_seqnum=259)) with mock.patch("wormhole._dilation.connection.log.err") as le: with self.assertRaises(ValueError): parse_record(b"\x07unknown") self.assertEqual(le.mock_calls, [mock.call("received unknown message type: {}".format( b"\x07unknown"))]) def test_encode(self): self.assertEqual(encode_record(KCM()), b"\x00") self.assertEqual(encode_record(Ping(ping_id=b"ping")), b"\x01ping") self.assertEqual(encode_record(Pong(ping_id=b"pong")), b"\x02pong") self.assertEqual(encode_record(Open(scid=65536, seqnum=16)), b"\x03\x00\x01\x00\x00\x00\x00\x00\x10") self.assertEqual(encode_record(Data(scid=65537, seqnum=17, data=b"dataaa")), b"\x04\x00\x01\x00\x01\x00\x00\x00\x11dataaa") self.assertEqual(encode_record(Close(scid=65538, seqnum=18)), b"\x05\x00\x01\x00\x02\x00\x00\x00\x12") self.assertEqual(encode_record(Ack(resp_seqnum=19)), b"\x06\x00\x00\x00\x13") with self.assertRaises(TypeError) as ar: encode_record("not a record") self.assertEqual(str(ar.exception), "not a record")
53.377778
85
0.594088
from __future__ import print_function, unicode_literals import mock from twisted.trial import unittest from ..._dilation.connection import (parse_record, encode_record, KCM, Ping, Pong, Open, Data, Close, Ack) class Parse(unittest.TestCase): def test_parse(self): self.assertEqual(parse_record(b"\x00"), KCM()) self.assertEqual(parse_record(b"\x01\x55\x44\x33\x22"), Ping(ping_id=b"\x55\x44\x33\x22")) self.assertEqual(parse_record(b"\x02\x55\x44\x33\x22"), Pong(ping_id=b"\x55\x44\x33\x22")) self.assertEqual(parse_record(b"\x03\x00\x00\x02\x01\x00\x00\x01\x00"), Open(scid=513, seqnum=256)) self.assertEqual(parse_record(b"\x04\x00\x00\x02\x02\x00\x00\x01\x01dataaa"), Data(scid=514, seqnum=257, data=b"dataaa")) self.assertEqual(parse_record(b"\x05\x00\x00\x02\x03\x00\x00\x01\x02"), Close(scid=515, seqnum=258)) self.assertEqual(parse_record(b"\x06\x00\x00\x01\x03"), Ack(resp_seqnum=259)) with mock.patch("wormhole._dilation.connection.log.err") as le: with self.assertRaises(ValueError): parse_record(b"\x07unknown") self.assertEqual(le.mock_calls, [mock.call("received unknown message type: {}".format( b"\x07unknown"))]) def test_encode(self): self.assertEqual(encode_record(KCM()), b"\x00") self.assertEqual(encode_record(Ping(ping_id=b"ping")), b"\x01ping") self.assertEqual(encode_record(Pong(ping_id=b"pong")), b"\x02pong") self.assertEqual(encode_record(Open(scid=65536, seqnum=16)), b"\x03\x00\x01\x00\x00\x00\x00\x00\x10") self.assertEqual(encode_record(Data(scid=65537, seqnum=17, data=b"dataaa")), b"\x04\x00\x01\x00\x01\x00\x00\x00\x11dataaa") self.assertEqual(encode_record(Close(scid=65538, seqnum=18)), b"\x05\x00\x01\x00\x02\x00\x00\x00\x12") self.assertEqual(encode_record(Ack(resp_seqnum=19)), b"\x06\x00\x00\x00\x13") with self.assertRaises(TypeError) as ar: encode_record("not a record") self.assertEqual(str(ar.exception), "not a record")
true
true
f7276c0f73e6ebdbc9164c77803a6a39d802249f
4,350
py
Python
tests/test_stream_xep_0047.py
marconfus/slixmpp
bcf186f42dc31d360e0a0af8a4b3aaf1e0b212aa
[ "BSD-3-Clause" ]
null
null
null
tests/test_stream_xep_0047.py
marconfus/slixmpp
bcf186f42dc31d360e0a0af8a4b3aaf1e0b212aa
[ "BSD-3-Clause" ]
null
null
null
tests/test_stream_xep_0047.py
marconfus/slixmpp
bcf186f42dc31d360e0a0af8a4b3aaf1e0b212aa
[ "BSD-3-Clause" ]
null
null
null
import asyncio import threading import time import unittest from slixmpp.test import SlixTest class TestInBandByteStreams(SlixTest): def setUp(self): self.stream_start(plugins=['xep_0047', 'xep_0030']) def tearDown(self): self.stream_close() def testOpenStream(self): """Test requesting a stream, successfully""" events = [] def on_stream_start(stream): events.append('ibb_stream_start') self.xmpp.add_event_handler('ibb_stream_start', on_stream_start) self.xmpp['xep_0047'].open_stream('tester@localhost/receiver', sid='testing') self.send(""" <iq type="set" to="tester@localhost/receiver" id="1"> <open xmlns="http://jabber.org/protocol/ibb" sid="testing" block-size="4096" stanza="iq" /> </iq> """) self.recv(""" <iq type="result" id="1" to="tester@localhost" from="tester@localhost/receiver" /> """) self.assertEqual(events, ['ibb_stream_start']) def testAysncOpenStream(self): """Test requesting a stream, aysnc""" events = set() def on_stream_start(stream): events.add('ibb_stream_start') def stream_callback(iq): events.add('callback') self.xmpp.add_event_handler('ibb_stream_start', on_stream_start) self.xmpp['xep_0047'].open_stream('tester@localhost/receiver', sid='testing', callback=stream_callback) self.send(""" <iq type="set" to="tester@localhost/receiver" id="1"> <open xmlns="http://jabber.org/protocol/ibb" sid="testing" block-size="4096" stanza="iq" /> </iq> """) self.recv(""" <iq type="result" id="1" to="tester@localhost" from="tester@localhost/receiver" /> """) self.assertEqual(events, {'ibb_stream_start', 'callback'}) async def testSendData(self): """Test sending data over an in-band bytestream.""" streams = [] data = [] def on_stream_start(stream): streams.append(stream) def on_stream_data(d): data.append(d['data']) self.xmpp.add_event_handler('ibb_stream_start', on_stream_start) self.xmpp.add_event_handler('ibb_stream_data', on_stream_data) self.xmpp['xep_0047'].open_stream('tester@localhost/receiver', sid='testing') self.send(""" <iq type="set" to="tester@localhost/receiver" id="1"> <open xmlns="http://jabber.org/protocol/ibb" sid="testing" block-size="4096" stanza="iq" /> </iq> """) self.recv(""" <iq type="result" id="1" to="tester@localhost" from="tester@localhost/receiver" /> """) stream = streams[0] # Test sending data out await stream.send("Testing") self.send(""" <iq type="set" id="2" from="tester@localhost" to="tester@localhost/receiver"> <data xmlns="http://jabber.org/protocol/ibb" seq="0" sid="testing"> VGVzdGluZw== </data> </iq> """) self.recv(""" <iq type="result" id="2" to="tester@localhost" from="tester@localhost/receiver" /> """) # Test receiving data self.recv(""" <iq type="set" id="A" to="tester@localhost" from="tester@localhost/receiver"> <data xmlns="http://jabber.org/protocol/ibb" seq="0" sid="testing"> aXQgd29ya3Mh </data> </iq> """) self.send(""" <iq type="result" id="A" to="tester@localhost/receiver" /> """) self.assertEqual(data, [b'it works!']) suite = unittest.TestLoader().loadTestsFromTestCase(TestInBandByteStreams)
27.018634
74
0.50092
import asyncio import threading import time import unittest from slixmpp.test import SlixTest class TestInBandByteStreams(SlixTest): def setUp(self): self.stream_start(plugins=['xep_0047', 'xep_0030']) def tearDown(self): self.stream_close() def testOpenStream(self): events = [] def on_stream_start(stream): events.append('ibb_stream_start') self.xmpp.add_event_handler('ibb_stream_start', on_stream_start) self.xmpp['xep_0047'].open_stream('tester@localhost/receiver', sid='testing') self.send(""" <iq type="set" to="tester@localhost/receiver" id="1"> <open xmlns="http://jabber.org/protocol/ibb" sid="testing" block-size="4096" stanza="iq" /> </iq> """) self.recv(""" <iq type="result" id="1" to="tester@localhost" from="tester@localhost/receiver" /> """) self.assertEqual(events, ['ibb_stream_start']) def testAysncOpenStream(self): events = set() def on_stream_start(stream): events.add('ibb_stream_start') def stream_callback(iq): events.add('callback') self.xmpp.add_event_handler('ibb_stream_start', on_stream_start) self.xmpp['xep_0047'].open_stream('tester@localhost/receiver', sid='testing', callback=stream_callback) self.send(""" <iq type="set" to="tester@localhost/receiver" id="1"> <open xmlns="http://jabber.org/protocol/ibb" sid="testing" block-size="4096" stanza="iq" /> </iq> """) self.recv(""" <iq type="result" id="1" to="tester@localhost" from="tester@localhost/receiver" /> """) self.assertEqual(events, {'ibb_stream_start', 'callback'}) async def testSendData(self): streams = [] data = [] def on_stream_start(stream): streams.append(stream) def on_stream_data(d): data.append(d['data']) self.xmpp.add_event_handler('ibb_stream_start', on_stream_start) self.xmpp.add_event_handler('ibb_stream_data', on_stream_data) self.xmpp['xep_0047'].open_stream('tester@localhost/receiver', sid='testing') self.send(""" <iq type="set" to="tester@localhost/receiver" id="1"> <open xmlns="http://jabber.org/protocol/ibb" sid="testing" block-size="4096" stanza="iq" /> </iq> """) self.recv(""" <iq type="result" id="1" to="tester@localhost" from="tester@localhost/receiver" /> """) stream = streams[0] await stream.send("Testing") self.send(""" <iq type="set" id="2" from="tester@localhost" to="tester@localhost/receiver"> <data xmlns="http://jabber.org/protocol/ibb" seq="0" sid="testing"> VGVzdGluZw== </data> </iq> """) self.recv(""" <iq type="result" id="2" to="tester@localhost" from="tester@localhost/receiver" /> """) self.recv(""" <iq type="set" id="A" to="tester@localhost" from="tester@localhost/receiver"> <data xmlns="http://jabber.org/protocol/ibb" seq="0" sid="testing"> aXQgd29ya3Mh </data> </iq> """) self.send(""" <iq type="result" id="A" to="tester@localhost/receiver" /> """) self.assertEqual(data, [b'it works!']) suite = unittest.TestLoader().loadTestsFromTestCase(TestInBandByteStreams)
true
true
f7276ccb81e55d56903c23dd551e1c32e13eedf8
402
py
Python
Lab-assignment/A-2/digitalRoot.py
HembramBeta777/Python-Programming
827611b0613d9d953d13fb04ea9b5c5ac3c510f2
[ "BSD-3-Clause" ]
2
2020-09-01T04:58:16.000Z
2021-01-30T03:45:52.000Z
Lab-assignment/A-2/digitalRoot.py
HembramBeta777/Python-Programming
827611b0613d9d953d13fb04ea9b5c5ac3c510f2
[ "BSD-3-Clause" ]
null
null
null
Lab-assignment/A-2/digitalRoot.py
HembramBeta777/Python-Programming
827611b0613d9d953d13fb04ea9b5c5ac3c510f2
[ "BSD-3-Clause" ]
null
null
null
# PROGRAM: To find the digital root of an integer # FILE: digitalRoot.py # CREATED BY: Santosh Hembram # DATED: 23-09-20 num = int(input("Enter an integer: ")) temp = num sum = 10 while(sum>=10): sum = 0 while(num!=0): dg = num % 10 sum = sum + dg num = num // 10 num = sum print("The digital root of ",temp,"is",sum)
15.461538
50
0.517413
num = int(input("Enter an integer: ")) temp = num sum = 10 while(sum>=10): sum = 0 while(num!=0): dg = num % 10 sum = sum + dg num = num // 10 num = sum print("The digital root of ",temp,"is",sum)
true
true
f7276d8b2cac2a3f653f6513bcab4a0e6a780d71
1,583
py
Python
airflow/migrations/versions/0101_a3bcd0914482_add_data_compressed_to_serialized_dag.py
npodewitz/airflow
511ea702d5f732582d018dad79754b54d5e53f9d
[ "Apache-2.0" ]
8,092
2016-04-27T20:32:29.000Z
2019-01-05T07:39:33.000Z
airflow/migrations/versions/0101_a3bcd0914482_add_data_compressed_to_serialized_dag.py
npodewitz/airflow
511ea702d5f732582d018dad79754b54d5e53f9d
[ "Apache-2.0" ]
2,961
2016-05-05T07:16:16.000Z
2019-01-05T08:47:59.000Z
airflow/migrations/versions/0101_a3bcd0914482_add_data_compressed_to_serialized_dag.py
npodewitz/airflow
511ea702d5f732582d018dad79754b54d5e53f9d
[ "Apache-2.0" ]
3,546
2016-05-04T20:33:16.000Z
2019-01-05T05:14:26.000Z
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """add data_compressed to serialized_dag Revision ID: a3bcd0914482 Revises: e655c0453f75 Create Date: 2022-02-03 22:40:59.841119 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = 'a3bcd0914482' down_revision = 'e655c0453f75' branch_labels = None depends_on = None airflow_version = '2.3.0' def upgrade(): with op.batch_alter_table('serialized_dag') as batch_op: batch_op.alter_column('data', existing_type=sa.JSON, nullable=True) batch_op.add_column(sa.Column('data_compressed', sa.LargeBinary, nullable=True)) def downgrade(): with op.batch_alter_table('serialized_dag') as batch_op: batch_op.alter_column('data', existing_type=sa.JSON, nullable=False) batch_op.drop_column('data_compressed')
32.979167
88
0.760581
import sqlalchemy as sa from alembic import op revision = 'a3bcd0914482' down_revision = 'e655c0453f75' branch_labels = None depends_on = None airflow_version = '2.3.0' def upgrade(): with op.batch_alter_table('serialized_dag') as batch_op: batch_op.alter_column('data', existing_type=sa.JSON, nullable=True) batch_op.add_column(sa.Column('data_compressed', sa.LargeBinary, nullable=True)) def downgrade(): with op.batch_alter_table('serialized_dag') as batch_op: batch_op.alter_column('data', existing_type=sa.JSON, nullable=False) batch_op.drop_column('data_compressed')
true
true
f7276e95cabbe199d785db08683a32a5ff10b6c4
3,062
py
Python
code/options.py
frizman04/language-style-transfer-python3
9110eb9d5b72d2926f805ac258915c0f1a369638
[ "Apache-2.0" ]
3
2018-07-11T07:41:58.000Z
2022-02-10T09:34:32.000Z
code/options.py
frizman04/language-style-transfer-python3
9110eb9d5b72d2926f805ac258915c0f1a369638
[ "Apache-2.0" ]
null
null
null
code/options.py
frizman04/language-style-transfer-python3
9110eb9d5b72d2926f805ac258915c0f1a369638
[ "Apache-2.0" ]
null
null
null
import sys import argparse import pprint def load_arguments(): argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument('--train', type=str, default='') argparser.add_argument('--dev', type=str, default='') argparser.add_argument('--test', type=str, default='') argparser.add_argument('--online_testing', type=bool, default=False) argparser.add_argument('--output', type=str, default='') argparser.add_argument('--vocab', type=str, default='') argparser.add_argument('--embedding', type=str, default='') argparser.add_argument('--model', type=str, default='') argparser.add_argument('--load_model', type=bool, default=False) argparser.add_argument('--batch_size', type=int, default=64) argparser.add_argument('--max_epochs', type=int, default=20) argparser.add_argument('--steps_per_checkpoint', type=int, default=1000) argparser.add_argument('--max_seq_length', type=int, default=20) argparser.add_argument('--max_train_size', type=int, default=-1) argparser.add_argument('--beam', type=int, default=1) argparser.add_argument('--dropout_keep_prob', type=float, default=0.5) argparser.add_argument('--n_layers', type=int, default=1) argparser.add_argument('--dim_y', type=int, default=200) argparser.add_argument('--dim_z', type=int, default=500) argparser.add_argument('--dim_emb', type=int, default=100) argparser.add_argument('--learning_rate', type=float, default=0.0001) #argparser.add_argument('--learning_rate_decay', # type=float, # default=0.5) argparser.add_argument('--rho', # loss_g - rho * loss_d type=float, default=1) argparser.add_argument('--gamma_init', # softmax(logit / gamma) type=float, default=1) argparser.add_argument('--gamma_decay', type=float, default=0.5) argparser.add_argument('--gamma_min', type=float, default=0.001) argparser.add_argument('--filter_sizes', type=str, default='3,4,5') argparser.add_argument('--n_filters', type=int, default=128) args = argparser.parse_args() print('------------------------------------------------') pp = pprint.PrettyPrinter(indent=4) pp.pprint(vars(args)) print('------------------------------------------------') return args
29.728155
81
0.497061
import sys import argparse import pprint def load_arguments(): argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument('--train', type=str, default='') argparser.add_argument('--dev', type=str, default='') argparser.add_argument('--test', type=str, default='') argparser.add_argument('--online_testing', type=bool, default=False) argparser.add_argument('--output', type=str, default='') argparser.add_argument('--vocab', type=str, default='') argparser.add_argument('--embedding', type=str, default='') argparser.add_argument('--model', type=str, default='') argparser.add_argument('--load_model', type=bool, default=False) argparser.add_argument('--batch_size', type=int, default=64) argparser.add_argument('--max_epochs', type=int, default=20) argparser.add_argument('--steps_per_checkpoint', type=int, default=1000) argparser.add_argument('--max_seq_length', type=int, default=20) argparser.add_argument('--max_train_size', type=int, default=-1) argparser.add_argument('--beam', type=int, default=1) argparser.add_argument('--dropout_keep_prob', type=float, default=0.5) argparser.add_argument('--n_layers', type=int, default=1) argparser.add_argument('--dim_y', type=int, default=200) argparser.add_argument('--dim_z', type=int, default=500) argparser.add_argument('--dim_emb', type=int, default=100) argparser.add_argument('--learning_rate', type=float, default=0.0001) argparser.add_argument('--rho', type=float, default=1) argparser.add_argument('--gamma_init', type=float, default=1) argparser.add_argument('--gamma_decay', type=float, default=0.5) argparser.add_argument('--gamma_min', type=float, default=0.001) argparser.add_argument('--filter_sizes', type=str, default='3,4,5') argparser.add_argument('--n_filters', type=int, default=128) args = argparser.parse_args() print('------------------------------------------------') pp = pprint.PrettyPrinter(indent=4) pp.pprint(vars(args)) print('------------------------------------------------') return args
true
true
f7276ecb99f6a3382aea6076e38bd2ab95a340d1
239
py
Python
tests/configs/fragment_config_overrides.py
aptdamia/jirahub
f12516254784db23367f96ad7e6bb1b127d9de3f
[ "BSD-3-Clause" ]
10
2018-06-18T19:46:21.000Z
2022-03-03T20:50:15.000Z
tests/configs/fragment_config_overrides.py
aptdamia/jirahub
f12516254784db23367f96ad7e6bb1b127d9de3f
[ "BSD-3-Clause" ]
19
2018-04-13T15:01:51.000Z
2022-01-20T21:21:15.000Z
tests/configs/fragment_config_overrides.py
aptdamia/jirahub
f12516254784db23367f96ad7e6bb1b127d9de3f
[ "BSD-3-Clause" ]
9
2018-04-04T19:14:21.000Z
2021-02-25T07:52:12.000Z
# This config is incomplete, but will specify all the required key # when combined with fragment_config_base.py. c.jira.project_key = "TEST" c.jira.max_retries = 7 c.jira.sync_milestones = False c.github.repository = "testing/test-repo"
26.555556
66
0.774059
c.jira.project_key = "TEST" c.jira.max_retries = 7 c.jira.sync_milestones = False c.github.repository = "testing/test-repo"
true
true
f7276f21393a47035bbe973f09006fec1326f4ec
4,735
py
Python
members/amit/clf/data_generator_binary.py
Leofltt/rg_sound_generation
8e79b4d9dce028def43284f80521a2ec61d0066c
[ "MIT" ]
null
null
null
members/amit/clf/data_generator_binary.py
Leofltt/rg_sound_generation
8e79b4d9dce028def43284f80521a2ec61d0066c
[ "MIT" ]
null
null
null
members/amit/clf/data_generator_binary.py
Leofltt/rg_sound_generation
8e79b4d9dce028def43284f80521a2ec61d0066c
[ "MIT" ]
null
null
null
import random import shutil import os import numpy as np import data_loader import audio_processing from typing import Dict from loguru import logger from tqdm import tqdm from pprint import pprint class DataGenerator: def __init__(self, conf: Dict, batch_size: int = 8): assert "csv_file_path" in conf assert "base_dir" in conf self.conf = conf.copy() self.batch_size = batch_size self.examples = data_loader.data_loader(conf) self.num_examples = len(self.examples) self.train = {0: [], 1: []} self.valid = {0: [], 1: []} self.train_counts = {0: 0, 1: 0} self.valid_counts = {0: 0, 1: 0} self.num_train = 0 self.num_valid = 0 self.classes = [0, 1] self.input_shapes = { "spec": (), "hpss": () } logger.info("DataGenerator instantiated") self.preprocess() logger.info("Preprocessing complete") def preprocess(self): logger.info("Preprocessing examples") logger.info(f"{self.input_shapes['spec']} = Current input shape for spec") folder = os.path.join(self.conf.get("preprocess_dir")) if self.conf.get("reset_data"): if os.path.isdir(folder): shutil.rmtree(folder) if not os.path.isdir(folder): os.mkdir(folder) min_level = 50 - self.conf.get("threshold") max_level = 50 + self.conf.get("threshold") valid_split = int(self.conf.get("valid_split") * 100) logger.info(f"Min level {min_level}, Max level {max_level}") for key, value in tqdm(self.examples.items()): audio_file_name = value["audio_file_name"] file_path = os.path.join(self.conf.get("base_dir"), f"{audio_file_name}.wav") current_class = 1 for j, feature in enumerate(self.conf.get("features")): current_val = int(value[feature]) current_class = -1 if current_val < min_level: current_class = 0 elif current_val > max_level: current_class = 1 if current_class == -1: continue target_file_path = os.path.join(self.conf.get("preprocess_dir"), audio_file_name) if not os.path.isfile(f"{target_file_path}.spec.npy"): spec, hpss = audio_processing.get_features(file_path, self.conf) self.input_shapes["spec"] = spec.shape self.input_shapes["hpss"] = hpss.shape np.save(f"{target_file_path}.spec", spec) np.save(f"{target_file_path}.hpss", hpss) elif len(self.input_shapes["spec"]) == 0: spec = np.load(f"{target_file_path}.spec.npy") hpss = np.load(f"{target_file_path}.hpss.npy") logger.info("Setting input shapes based on previous files") logger.info(f"{spec.shape}, {hpss.shape}") self.input_shapes["spec"] = spec.shape self.input_shapes["hpss"] = hpss.shape if random.randint(0, 99) < valid_split: self.valid[current_class].append(target_file_path) self.valid_counts[current_class] += 1 else: self.train[current_class].append(target_file_path) self.train_counts[current_class] += 1 self.num_train = sum(list(self.train_counts.values())) self.num_valid = sum(list(self.train_counts.values())) logger.info("Class counts in training set") pprint(self.train_counts) logger.info("Class counts in validation set") pprint(self.valid_counts) def generator(self, set_name: str): assert set_name in ["train", "valid"], "Set name must be either train or valid" while True: spec_batch = np.zeros((self.batch_size,) + self.input_shapes["spec"]) hpss_batch = np.zeros((self.batch_size,) + self.input_shapes["hpss"]) y_batch = np.zeros((self.batch_size, )) current_set = eval(f"self.{set_name}") for i in range(0, self.batch_size): target_class = random.choice([0, 1]) example_file = random.choice(current_set[target_class]) example_spec = np.load(f"{example_file}.spec.npy") * self.conf.get("scale_factor") example_hpss = np.load(f"{example_file}.hpss.npy") * self.conf.get("scale_factor") spec_batch[i] = example_spec hpss_batch[i] = example_hpss y_batch[i] = target_class yield {"spec": spec_batch, "hpss": hpss_batch}, {"output": y_batch}
39.132231
98
0.583316
import random import shutil import os import numpy as np import data_loader import audio_processing from typing import Dict from loguru import logger from tqdm import tqdm from pprint import pprint class DataGenerator: def __init__(self, conf: Dict, batch_size: int = 8): assert "csv_file_path" in conf assert "base_dir" in conf self.conf = conf.copy() self.batch_size = batch_size self.examples = data_loader.data_loader(conf) self.num_examples = len(self.examples) self.train = {0: [], 1: []} self.valid = {0: [], 1: []} self.train_counts = {0: 0, 1: 0} self.valid_counts = {0: 0, 1: 0} self.num_train = 0 self.num_valid = 0 self.classes = [0, 1] self.input_shapes = { "spec": (), "hpss": () } logger.info("DataGenerator instantiated") self.preprocess() logger.info("Preprocessing complete") def preprocess(self): logger.info("Preprocessing examples") logger.info(f"{self.input_shapes['spec']} = Current input shape for spec") folder = os.path.join(self.conf.get("preprocess_dir")) if self.conf.get("reset_data"): if os.path.isdir(folder): shutil.rmtree(folder) if not os.path.isdir(folder): os.mkdir(folder) min_level = 50 - self.conf.get("threshold") max_level = 50 + self.conf.get("threshold") valid_split = int(self.conf.get("valid_split") * 100) logger.info(f"Min level {min_level}, Max level {max_level}") for key, value in tqdm(self.examples.items()): audio_file_name = value["audio_file_name"] file_path = os.path.join(self.conf.get("base_dir"), f"{audio_file_name}.wav") current_class = 1 for j, feature in enumerate(self.conf.get("features")): current_val = int(value[feature]) current_class = -1 if current_val < min_level: current_class = 0 elif current_val > max_level: current_class = 1 if current_class == -1: continue target_file_path = os.path.join(self.conf.get("preprocess_dir"), audio_file_name) if not os.path.isfile(f"{target_file_path}.spec.npy"): spec, hpss = audio_processing.get_features(file_path, self.conf) self.input_shapes["spec"] = spec.shape self.input_shapes["hpss"] = hpss.shape np.save(f"{target_file_path}.spec", spec) np.save(f"{target_file_path}.hpss", hpss) elif len(self.input_shapes["spec"]) == 0: spec = np.load(f"{target_file_path}.spec.npy") hpss = np.load(f"{target_file_path}.hpss.npy") logger.info("Setting input shapes based on previous files") logger.info(f"{spec.shape}, {hpss.shape}") self.input_shapes["spec"] = spec.shape self.input_shapes["hpss"] = hpss.shape if random.randint(0, 99) < valid_split: self.valid[current_class].append(target_file_path) self.valid_counts[current_class] += 1 else: self.train[current_class].append(target_file_path) self.train_counts[current_class] += 1 self.num_train = sum(list(self.train_counts.values())) self.num_valid = sum(list(self.train_counts.values())) logger.info("Class counts in training set") pprint(self.train_counts) logger.info("Class counts in validation set") pprint(self.valid_counts) def generator(self, set_name: str): assert set_name in ["train", "valid"], "Set name must be either train or valid" while True: spec_batch = np.zeros((self.batch_size,) + self.input_shapes["spec"]) hpss_batch = np.zeros((self.batch_size,) + self.input_shapes["hpss"]) y_batch = np.zeros((self.batch_size, )) current_set = eval(f"self.{set_name}") for i in range(0, self.batch_size): target_class = random.choice([0, 1]) example_file = random.choice(current_set[target_class]) example_spec = np.load(f"{example_file}.spec.npy") * self.conf.get("scale_factor") example_hpss = np.load(f"{example_file}.hpss.npy") * self.conf.get("scale_factor") spec_batch[i] = example_spec hpss_batch[i] = example_hpss y_batch[i] = target_class yield {"spec": spec_batch, "hpss": hpss_batch}, {"output": y_batch}
true
true
f727702ee7977a991a5617a1ff32f85463c61f40
4,108
py
Python
feedback_system/findTable.py
bshrram/Graduation-Project---Omnidirectional-Conveyor-Table
6414fbcb3d53f3c3351c25ac8b48aa73397c250d
[ "MIT" ]
1
2020-09-24T05:06:17.000Z
2020-09-24T05:06:17.000Z
feedback_system/findTable.py
bshrram/Graduation-Project---Omnidirectional-Conveyor-Table
6414fbcb3d53f3c3351c25ac8b48aa73397c250d
[ "MIT" ]
null
null
null
feedback_system/findTable.py
bshrram/Graduation-Project---Omnidirectional-Conveyor-Table
6414fbcb3d53f3c3351c25ac8b48aa73397c250d
[ "MIT" ]
1
2020-12-13T13:31:08.000Z
2020-12-13T13:31:08.000Z
import numpy as np import cv2 as cv flann_params= dict(algorithm = 6, table_number = 6, # 12 key_size = 12, # 20 multi_probe_level = 1) #2 def init_feature(): """initialize feature detector and matcher algorithm """ detector = cv.ORB_create(3000) norm = cv.NORM_HAMMING #matcher = cv.BFMatcher(norm) matcher = cv.FlannBasedMatcher(flann_params, {}) return detector, matcher def filter_matches(kp1, kp2, matches, ratio = 0.8): """filter matches to keep strong matches only """ mkp1, mkp2 = [], [] for m in matches: if len(m) == 2 and m[0].distance < m[1].distance * ratio: m = m[0] mkp1.append( kp1[m.queryIdx] ) mkp2.append( kp2[m.trainIdx] ) p1 = np.float32([kp.pt for kp in mkp1]) p2 = np.float32([kp.pt for kp in mkp2]) kp_pairs = zip(mkp1, mkp2) return p1, p2, list(kp_pairs) c = [] def explore_match(win, img1, img2, kp_pairs, status = None, H = None): h1, w1 = img1.shape[:2] h2, w2 = img2.shape[:2] vis = np.zeros((max(h1, h2), w1+w2, 3), np.uint8) vis[:h1, :w1, :3] = img1 vis[:h2, w1:w1+w2, :3] = img2 img3 = vis h3, w3 = img3.shape[:2] if H is not None: corners = np.float32([[0, 0], [w1, 0], [w1, h1], [0, h1]]) corners1 = np.float32( cv.perspectiveTransform(corners.reshape(1, -1, 2), H).reshape(-1, 2) + (w1, 0)) corners = np.int32( cv.perspectiveTransform(corners.reshape(1, -1, 2), H).reshape(-1, 2) + (w1, 0) ) c = corners cv.polylines(vis, [corners], True, (0, 0, 255)) if status is None: status = np.ones(len(kp_pairs), np.bool_) p1, p2 = [], [] for kpp in kp_pairs: p1.append(np.int32(kpp[0].pt)) p2.append(np.int32(np.array(kpp[1].pt) + [w1, 0])) green = (0, 255, 0) red = (0, 0, 255) for (x1, y1), (x2, y2), inlier in zip(p1, p2, status): if inlier: col = green cv.circle(vis, (x1, y1), 2, col, -1) cv.circle(vis, (x2, y2), 2, col, -1) else: col = red r = 2 thickness = 3 cv.line(vis, (x1-r, y1-r), (x1+r, y1+r), col, thickness) cv.line(vis, (x1-r, y1+r), (x1+r, y1-r), col, thickness) cv.line(vis, (x2-r, y2-r), (x2+r, y2+r), col, thickness) cv.line(vis, (x2-r, y2+r), (x2+r, y2-r), col, thickness) for (x1, y1), (x2, y2), inlier in zip(p1, p2, status): if inlier: cv.line(vis, (x1, y1), (x2, y2), green) cv.imshow(win, vis) return corners1 scale_percent =25 img1 = cv.imread(cv.samples.findFile('table7A.jpg')) width = int(img1.shape[1] * scale_percent / 100) height = int(img1.shape[0] * scale_percent / 100) #img1 = cv.resize(img1, (width,height)) detector, matcher = init_feature() # apply orb on table image kp1, desc1 = detector.detectAndCompute(img1, None) def getCorners(frame): # apply orb on frame kp2, desc2 = detector.detectAndCompute(frame, None) print('matching...') raw_matches = matcher.knnMatch(desc1, trainDescriptors = desc2, k = 2) #filter matches and keep strong matches p1, p2, kp_pairs = filter_matches(kp1, kp2, raw_matches) if len(p1) >= 4: # H: transformation matrix H, status = cv.findHomography(p1, p2, cv.RANSAC, 5.0) print('%d / %d inliers/matched' % (np.sum(status), len(status))) else: H, status = None, None print('%d matches found, not enough for homography estimation' % len(p1)) corners = explore_match('find_table', img1, frame, kp_pairs, status, H) return corners def getTableFromFrame (corners, frame): h1, w1 = img1.shape[:2] h2, w2 = frame.shape[:2] vis = np.zeros((max(h1, h2), w1+w2, 3), np.uint8) vis[:h1, :w1, :3] = img1 vis[:h2, w1:w1+w2, :3] = frame pts1 = corners pts2 = np.float32([[0,0],[w1,0],[w1,h1], [0,h1]]) M = cv.getPerspectiveTransform(pts1,pts2) # print((w1, h1)) dst = cv.warpPerspective(vis, M,(w1,h1)) return dst
31.844961
110
0.565725
import numpy as np import cv2 as cv flann_params= dict(algorithm = 6, table_number = 6, key_size = 12, multi_probe_level = 1) def init_feature(): detector = cv.ORB_create(3000) norm = cv.NORM_HAMMING matcher = cv.FlannBasedMatcher(flann_params, {}) return detector, matcher def filter_matches(kp1, kp2, matches, ratio = 0.8): mkp1, mkp2 = [], [] for m in matches: if len(m) == 2 and m[0].distance < m[1].distance * ratio: m = m[0] mkp1.append( kp1[m.queryIdx] ) mkp2.append( kp2[m.trainIdx] ) p1 = np.float32([kp.pt for kp in mkp1]) p2 = np.float32([kp.pt for kp in mkp2]) kp_pairs = zip(mkp1, mkp2) return p1, p2, list(kp_pairs) c = [] def explore_match(win, img1, img2, kp_pairs, status = None, H = None): h1, w1 = img1.shape[:2] h2, w2 = img2.shape[:2] vis = np.zeros((max(h1, h2), w1+w2, 3), np.uint8) vis[:h1, :w1, :3] = img1 vis[:h2, w1:w1+w2, :3] = img2 img3 = vis h3, w3 = img3.shape[:2] if H is not None: corners = np.float32([[0, 0], [w1, 0], [w1, h1], [0, h1]]) corners1 = np.float32( cv.perspectiveTransform(corners.reshape(1, -1, 2), H).reshape(-1, 2) + (w1, 0)) corners = np.int32( cv.perspectiveTransform(corners.reshape(1, -1, 2), H).reshape(-1, 2) + (w1, 0) ) c = corners cv.polylines(vis, [corners], True, (0, 0, 255)) if status is None: status = np.ones(len(kp_pairs), np.bool_) p1, p2 = [], [] for kpp in kp_pairs: p1.append(np.int32(kpp[0].pt)) p2.append(np.int32(np.array(kpp[1].pt) + [w1, 0])) green = (0, 255, 0) red = (0, 0, 255) for (x1, y1), (x2, y2), inlier in zip(p1, p2, status): if inlier: col = green cv.circle(vis, (x1, y1), 2, col, -1) cv.circle(vis, (x2, y2), 2, col, -1) else: col = red r = 2 thickness = 3 cv.line(vis, (x1-r, y1-r), (x1+r, y1+r), col, thickness) cv.line(vis, (x1-r, y1+r), (x1+r, y1-r), col, thickness) cv.line(vis, (x2-r, y2-r), (x2+r, y2+r), col, thickness) cv.line(vis, (x2-r, y2+r), (x2+r, y2-r), col, thickness) for (x1, y1), (x2, y2), inlier in zip(p1, p2, status): if inlier: cv.line(vis, (x1, y1), (x2, y2), green) cv.imshow(win, vis) return corners1 scale_percent =25 img1 = cv.imread(cv.samples.findFile('table7A.jpg')) width = int(img1.shape[1] * scale_percent / 100) height = int(img1.shape[0] * scale_percent / 100) detector, matcher = init_feature() kp1, desc1 = detector.detectAndCompute(img1, None) def getCorners(frame): kp2, desc2 = detector.detectAndCompute(frame, None) print('matching...') raw_matches = matcher.knnMatch(desc1, trainDescriptors = desc2, k = 2) p1, p2, kp_pairs = filter_matches(kp1, kp2, raw_matches) if len(p1) >= 4: H, status = cv.findHomography(p1, p2, cv.RANSAC, 5.0) print('%d / %d inliers/matched' % (np.sum(status), len(status))) else: H, status = None, None print('%d matches found, not enough for homography estimation' % len(p1)) corners = explore_match('find_table', img1, frame, kp_pairs, status, H) return corners def getTableFromFrame (corners, frame): h1, w1 = img1.shape[:2] h2, w2 = frame.shape[:2] vis = np.zeros((max(h1, h2), w1+w2, 3), np.uint8) vis[:h1, :w1, :3] = img1 vis[:h2, w1:w1+w2, :3] = frame pts1 = corners pts2 = np.float32([[0,0],[w1,0],[w1,h1], [0,h1]]) M = cv.getPerspectiveTransform(pts1,pts2) dst = cv.warpPerspective(vis, M,(w1,h1)) return dst
true
true
f72771a425e944529c8133e292bae69e1f9dc774
1,013
py
Python
tensorlayer/package_info.py
Officium/tensorlayer
89bd7646cff2bc77c6569f2a51d48bc1e80229e4
[ "Apache-2.0" ]
2
2020-10-18T15:43:49.000Z
2020-10-27T14:52:48.000Z
tensorlayer/package_info.py
sheiiva/tensorlayer
5d692fe87ac4d4439506b5c4827399fd5a8ab5da
[ "Apache-2.0" ]
null
null
null
tensorlayer/package_info.py
sheiiva/tensorlayer
5d692fe87ac4d4439506b5c4827399fd5a8ab5da
[ "Apache-2.0" ]
1
2020-10-15T13:15:40.000Z
2020-10-15T13:15:40.000Z
#! /usr/bin/python # -*- coding: utf-8 -*- """Deep learning and Reinforcement learning library for Researchers and Engineers.""" MAJOR = 2 MINOR = 1 PATCH = 1 PRE_RELEASE = '' # Use the following formatting: (major, minor, patch, prerelease) VERSION = (MAJOR, MINOR, PATCH, PRE_RELEASE) __shortversion__ = '.'.join(map(str, VERSION[:3])) __version__ = '.'.join(map(str, VERSION[:3])) + ''.join(VERSION[3:]) __package_name__ = 'tensorlayer' __contact_names__ = 'TensorLayer Contributors' __contact_emails__ = 'tensorlayer@gmail.com' __homepage__ = 'http://tensorlayer.readthedocs.io/en/latest/' __repository_url__ = 'https://github.com/tensorlayer/tensorlayer' __download_url__ = 'https://github.com/tensorlayer/tensorlayer' __description__ = 'High Level Tensorflow Deep Learning Library for Researcher and Engineer.' __license__ = 'apache' __keywords__ = 'deep learning, machine learning, computer vision, nlp, ' __keywords__ += 'supervised learning, unsupervised learning, reinforcement learning, tensorflow'
40.52
96
0.757157
MAJOR = 2 MINOR = 1 PATCH = 1 PRE_RELEASE = '' VERSION = (MAJOR, MINOR, PATCH, PRE_RELEASE) __shortversion__ = '.'.join(map(str, VERSION[:3])) __version__ = '.'.join(map(str, VERSION[:3])) + ''.join(VERSION[3:]) __package_name__ = 'tensorlayer' __contact_names__ = 'TensorLayer Contributors' __contact_emails__ = 'tensorlayer@gmail.com' __homepage__ = 'http://tensorlayer.readthedocs.io/en/latest/' __repository_url__ = 'https://github.com/tensorlayer/tensorlayer' __download_url__ = 'https://github.com/tensorlayer/tensorlayer' __description__ = 'High Level Tensorflow Deep Learning Library for Researcher and Engineer.' __license__ = 'apache' __keywords__ = 'deep learning, machine learning, computer vision, nlp, ' __keywords__ += 'supervised learning, unsupervised learning, reinforcement learning, tensorflow'
true
true
f7277265e7244b7ff4545ccd5788d0ae944adadd
167
py
Python
setup.py
contolini/regulations-site
c31a9ce3097910877657f61b4c19a4ccbd0f967f
[ "CC0-1.0" ]
null
null
null
setup.py
contolini/regulations-site
c31a9ce3097910877657f61b4c19a4ccbd0f967f
[ "CC0-1.0" ]
null
null
null
setup.py
contolini/regulations-site
c31a9ce3097910877657f61b4c19a4ccbd0f967f
[ "CC0-1.0" ]
null
null
null
from setuptools import setup, find_packages setup( name = "regulations", version = "0.1.0", license = "public domain", packages = find_packages() )
18.555556
43
0.646707
from setuptools import setup, find_packages setup( name = "regulations", version = "0.1.0", license = "public domain", packages = find_packages() )
true
true
f7277275036c1c4151a7b860aa018f1c5a139255
3,246
py
Python
scripts/ServerPoolMachinesHealth.py
sumedhpb/TAF
fc6f4cb8dc0b8234393f2e52a7b4a1aa723d9449
[ "Apache-2.0" ]
null
null
null
scripts/ServerPoolMachinesHealth.py
sumedhpb/TAF
fc6f4cb8dc0b8234393f2e52a7b4a1aa723d9449
[ "Apache-2.0" ]
null
null
null
scripts/ServerPoolMachinesHealth.py
sumedhpb/TAF
fc6f4cb8dc0b8234393f2e52a7b4a1aa723d9449
[ "Apache-2.0" ]
null
null
null
from com.jcraft.jsch import JSchException from com.jcraft.jsch import JSch from org.python.core.util import FileUtil from java.time import Duration from com.couchbase.client.java import Cluster, ClusterOptions from com.couchbase.client.java.env import ClusterEnvironment from com.couchbase.client.core.env import TimeoutConfig, IoConfig import sys failed = [] swapiness_cmd = "echo 0 > /proc/sys/vm/swappiness;echo \"net.ipv4.conf.all.arp_notify = 1\" > /etc/sysctl.conf;echo \"#Set swappiness to 0 to avoid swapping\" >> /etc/sysctl.conf;echo vm.swappiness = 0 >> /etc/sysctl.conf" thp_cmd = "echo never > /sys/kernel/mm/transparent_hugepage/enabled" disable_firewall = "systemctl stop firewalld; systemctl disable firewalld; ls -l /data" ulimit_cmd = "ulimit -n 500000;echo \"* soft nofile 500000\" > /etc/security/limits.conf;echo \"* hard nofile 500000\" >> /etc/security/limits.conf;" def run(command, server): output = [] error = [] jsch = JSch() session = jsch.getSession("root", server, 22) session.setPassword("couchbase") session.setConfig("StrictHostKeyChecking", "no") try: session.connect(10000) except JSchException: failed.append(server) try: _ssh_client = session.openChannel("exec") _ssh_client.setInputStream(None) _ssh_client.setErrStream(None) instream = _ssh_client.getInputStream() errstream = _ssh_client.getErrStream() _ssh_client.setCommand(command) _ssh_client.connect() fu1 = FileUtil.wrap(instream) for line in fu1.readlines(): output.append(line) fu1.close() fu2 = FileUtil.wrap(errstream) for line in fu2.readlines(): error.append(line) fu2.close() _ssh_client.disconnect() session.disconnect() except JSchException as e: print("JSch exception on %s: %s" % (server, str(e))) return output, error def execute(cmd="free -m"): cluster_env = ClusterEnvironment.builder().ioConfig(IoConfig.numKvConnections(25)).timeoutConfig(TimeoutConfig.builder().connectTimeout(Duration.ofSeconds(20)).kvTimeout(Duration.ofSeconds(10))) cluster_options = ClusterOptions.clusterOptions("Administrator", "esabhcuoc").environment(cluster_env.build()) cluster = Cluster.connect("172.23.104.162", cluster_options) STATEMENT = "select meta().id from `QE-server-pool` where os='centos' and '12hrreg' in poolId or 'regression' in poolId or 'magmareg' in poolId;" result = cluster.query(STATEMENT); count = 1 for server in result.rowsAsObject(): server = server.get("id") print("--+--+--+--+-- %s. SERVER: %s --+--+--+--+--" % (count, server)) count += 1 output, error = run(cmd, server) if output: print(output) if error: print(error) try: param = sys.argv[1] if "thp" in param.lower(): execute(thp_cmd) if "firewall" in param.lower(): execute(disable_firewall) if "swapiness" in param.lower(): execute(swapiness_cmd) if "ulimit" in param.lower(): execute(ulimit_cmd) except: execute() if failed: for server in failed: print("ssh failed: %s" % server)
37.744186
222
0.66451
from com.jcraft.jsch import JSchException from com.jcraft.jsch import JSch from org.python.core.util import FileUtil from java.time import Duration from com.couchbase.client.java import Cluster, ClusterOptions from com.couchbase.client.java.env import ClusterEnvironment from com.couchbase.client.core.env import TimeoutConfig, IoConfig import sys failed = [] swapiness_cmd = "echo 0 > /proc/sys/vm/swappiness;echo \"net.ipv4.conf.all.arp_notify = 1\" > /etc/sysctl.conf;echo \" thp_cmd = "echo never > /sys/kernel/mm/transparent_hugepage/enabled" disable_firewall = "systemctl stop firewalld; systemctl disable firewalld; ls -l /data" ulimit_cmd = "ulimit -n 500000;echo \"* soft nofile 500000\" > /etc/security/limits.conf;echo \"* hard nofile 500000\" >> /etc/security/limits.conf;" def run(command, server): output = [] error = [] jsch = JSch() session = jsch.getSession("root", server, 22) session.setPassword("couchbase") session.setConfig("StrictHostKeyChecking", "no") try: session.connect(10000) except JSchException: failed.append(server) try: _ssh_client = session.openChannel("exec") _ssh_client.setInputStream(None) _ssh_client.setErrStream(None) instream = _ssh_client.getInputStream() errstream = _ssh_client.getErrStream() _ssh_client.setCommand(command) _ssh_client.connect() fu1 = FileUtil.wrap(instream) for line in fu1.readlines(): output.append(line) fu1.close() fu2 = FileUtil.wrap(errstream) for line in fu2.readlines(): error.append(line) fu2.close() _ssh_client.disconnect() session.disconnect() except JSchException as e: print("JSch exception on %s: %s" % (server, str(e))) return output, error def execute(cmd="free -m"): cluster_env = ClusterEnvironment.builder().ioConfig(IoConfig.numKvConnections(25)).timeoutConfig(TimeoutConfig.builder().connectTimeout(Duration.ofSeconds(20)).kvTimeout(Duration.ofSeconds(10))) cluster_options = ClusterOptions.clusterOptions("Administrator", "esabhcuoc").environment(cluster_env.build()) cluster = Cluster.connect("172.23.104.162", cluster_options) STATEMENT = "select meta().id from `QE-server-pool` where os='centos' and '12hrreg' in poolId or 'regression' in poolId or 'magmareg' in poolId;" result = cluster.query(STATEMENT); count = 1 for server in result.rowsAsObject(): server = server.get("id") print("--+--+--+--+-- %s. SERVER: %s --+--+--+--+--" % (count, server)) count += 1 output, error = run(cmd, server) if output: print(output) if error: print(error) try: param = sys.argv[1] if "thp" in param.lower(): execute(thp_cmd) if "firewall" in param.lower(): execute(disable_firewall) if "swapiness" in param.lower(): execute(swapiness_cmd) if "ulimit" in param.lower(): execute(ulimit_cmd) except: execute() if failed: for server in failed: print("ssh failed: %s" % server)
true
true
f727740bd33f10993c9982599ba782f10061bf7f
2,831
py
Python
Bigeleisen_KIE.py
valkenzz/Bigeleisen_KIE
aa82ee63c77be2e9d0bd97702c297aa70dfaa362
[ "MIT" ]
1
2021-06-25T22:48:39.000Z
2021-06-25T22:48:39.000Z
Bigeleisen_KIE.py
valkenzz/Bigeleisen_KIE
aa82ee63c77be2e9d0bd97702c297aa70dfaa362
[ "MIT" ]
null
null
null
Bigeleisen_KIE.py
valkenzz/Bigeleisen_KIE
aa82ee63c77be2e9d0bd97702c297aa70dfaa362
[ "MIT" ]
null
null
null
#Importation : import pandas as pd import numpy as np ################################################ #Parameters : #Planck constant (J/Hz) h=6.62607004*10**-34 #Boltzmann constant (J/K) kB=1.38064852*10**-23 #Light velocity in vaccum (m/s) c=299792458.0 #################################################################################### #Functions: ###################################################################################### #We check for errors : #We check if all values are positiv for initial states def CheckPositiv(Data): if len(Data)!=len([i for i in Data if (i>0)]): print("At least one initial state hasn't every frequency that are positiv") def error(isH,isD,tsH,tsD): CheckPositiv(isH) CheckPositiv(isD) ##################################################################################### #Function which takes the lists of vibration frequencies of 2 states to give the product of the ratio of frequencies def Operation(Data1,Data2): if len(Data1)!=len(Data2): print("The number of frequencies isn't the same for two same states") return x=1 for i in range(len(Data1)): x=x*Data1[i]/Data2[i] return x #Function which takes one list of vibration frequencies to give the sinh of Ui = h*x/(kB*T) according to the Biegelheisen equation def Ui(Data,T): return pd.Series(Data).apply(lambda x : np.sinh(float(x)*((h*100*c)/(2.0*kB*float(T))))) #Function which takes in entry the lists of frequencies (cm-1) and the temperature (K) and gives the KIE #isH is the vibration frequencies of the molecule containing the light isotope at the initial state #isD is the vibration frequencies of the molecule containing the heavy isotope at the initial state #tsH is the vibration frequencies of the molecule containing the light isotope at the transition state #tsD is the vibration frequencies of the molecule containing the heavy isotope at the transition state #T is the temperature in Kelvin def KIE(isH,isD,tsH,tsD,T): error(isH,isD,tsH,tsD) #We calculate the sinh of h*x/(kB*T) UisH=Ui(isH,T).tolist() UtsH=Ui(tsH,T).tolist() UisD=Ui(isD,T).tolist() UtsD=Ui(tsD,T).tolist() ####################### #We begin to calculate the ratio of the two imaginary frequencies op1=tsH[0]/tsD[0] Result=op1 #We calculate the second factor Result=Result*Operation(tsH[1:],tsD[1:]) #We calculate the third factor Result=Result*Operation(isD,isH) #We calculate the fourth factor Result=Result*Operation(UtsD[1:],UtsH[1:]) #We calculate the fifth factor Result=Result*Operation(UisH,UisD) return Result ####################################################################################
37.746667
131
0.585306
import pandas as pd import numpy as np
true
true
f727743056c35927215b3d1cff28914c0160ba53
1,714
py
Python
examples/python/modulation-example.py
ideoforms/signalflow
1283cdf565d004495f1561d4d0683d51c11da50a
[ "MIT" ]
61
2020-10-12T11:46:09.000Z
2022-02-07T04:26:05.000Z
examples/python/modulation-example.py
ideoforms/signalflow
1283cdf565d004495f1561d4d0683d51c11da50a
[ "MIT" ]
26
2020-10-07T20:25:26.000Z
2022-03-25T11:40:57.000Z
examples/python/modulation-example.py
ideoforms/signalflow
1283cdf565d004495f1561d4d0683d51c11da50a
[ "MIT" ]
6
2021-02-27T19:50:25.000Z
2021-11-09T11:02:20.000Z
#!/usr/bin/env python3 #------------------------------------------------------------------------ # SignalFlow: Modulation example. #------------------------------------------------------------------------ from signalflow import * #------------------------------------------------------------------------ # Create the global processing graph. #------------------------------------------------------------------------ graph = AudioGraph(start=True) graph.show_status(1) #------------------------------------------------------------------------ # Create a regular impulse that is used to trigger an envelope and S&H. #------------------------------------------------------------------------ clock = Impulse(8) frequency = ScaleLinExp(SawLFO(0.2), 0, 1, 200, 2000) sample_hold = SampleAndHold(frequency, clock) sine = TriangleOscillator(sample_hold) * 0.5 env = EnvelopeASR(attack=0.001, sustain=0.001, release=0.1, clock=clock) #------------------------------------------------------------------------ # Apply the envelope, and stereo pan between speakers. #------------------------------------------------------------------------ mono = sine * env stereo = StereoPanner(mono, SineLFO(0.5, -1, 1)) #------------------------------------------------------------------------ # Add some delay. #------------------------------------------------------------------------ delay1 = CombDelay(mono, 0.1, 0.8) delay2 = OneTapDelay(CombDelay(mono, 0.05, 0.8), 0.125) stereo = stereo + ChannelArray([ delay1, delay2 ]) * 0.2 #------------------------------------------------------------------------ # Play the output. #------------------------------------------------------------------------ graph.play(stereo) graph.wait()
41.804878
73
0.351225
from signalflow import * graph = AudioGraph(start=True) graph.show_status(1) clock = Impulse(8) frequency = ScaleLinExp(SawLFO(0.2), 0, 1, 200, 2000) sample_hold = SampleAndHold(frequency, clock) sine = TriangleOscillator(sample_hold) * 0.5 env = EnvelopeASR(attack=0.001, sustain=0.001, release=0.1, clock=clock) mono = sine * env stereo = StereoPanner(mono, SineLFO(0.5, -1, 1)) delay1 = CombDelay(mono, 0.1, 0.8) delay2 = OneTapDelay(CombDelay(mono, 0.05, 0.8), 0.125) stereo = stereo + ChannelArray([ delay1, delay2 ]) * 0.2 graph.play(stereo) graph.wait()
true
true
f7277478cfed614fa4d55c97d1352a6fcb46bccc
2,908
py
Python
cifar10/custom_models.py
apexnetai/cifar-10-guide
7c76f310e93da3a229ce9d66defd770ee1c7dc56
[ "Apache-2.0" ]
null
null
null
cifar10/custom_models.py
apexnetai/cifar-10-guide
7c76f310e93da3a229ce9d66defd770ee1c7dc56
[ "Apache-2.0" ]
null
null
null
cifar10/custom_models.py
apexnetai/cifar-10-guide
7c76f310e93da3a229ce9d66defd770ee1c7dc56
[ "Apache-2.0" ]
null
null
null
import torch import torch.nn as nn import torch.nn.functional as F import torchvision class CustomResnetV1(nn.Module): def __init__(self): super(CustomResnetV1, self).__init__() self.resnet = torchvision.models.resnet18(pretrained=True) self.resnet.conv1 = nn.Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(0, 0), bias=False) self.resnet.fc = nn.Linear(512, 256) self.bn1a = nn.BatchNorm1d(256) self.fc11 = nn.Linear(256, 256) self.fc12 = nn.Linear(256, 256) self.bn1b = nn.BatchNorm1d(256) self.fc13 = nn.Linear(256, 256) self.fc14 = nn.Linear(256, 256) self.bn1c = nn.BatchNorm1d(256) self.fc15 = nn.Linear(256, 256) self.fc16 = nn.Linear(256, 256) self.fc_down1 = nn.Linear(256, 128) self.bn2a = nn.BatchNorm1d(128) self.fc21 = nn.Linear(128, 128) self.fc22 = nn.Linear(128, 128) self.bn2b = nn.BatchNorm1d(128) self.fc23 = nn.Linear(128, 128) self.fc24 = nn.Linear(128, 128) self.bn2c = nn.BatchNorm1d(128) self.fc25 = nn.Linear(128, 128) self.fc26 = nn.Linear(128, 128) self.fc_down2 = nn.Linear(128, 64) self.bn3a = nn.BatchNorm1d(64) self.fc31 = nn.Linear(64, 64) self.fc32 = nn.Linear(64, 64) self.bn3b = nn.BatchNorm1d(64) self.fc33 = nn.Linear(64, 64) self.fc34 = nn.Linear(64, 64) self.bn3c = nn.BatchNorm1d(64) self.fc35 = nn.Linear(64, 64) self.fc36 = nn.Linear(64, 64) self.fc4 = nn.Linear(64, 10) #self.drop1 = nn.Dropout2d(0.5) def forward(self, x): x_ = F.relu(self.resnet(x)) x = self.bn1a(x_) x = F.relu(self.fc11(x)) x = F.relu(self.fc12(x)) x_ = torch.add(x, x_) x = self.bn1b(x_) x = F.relu(self.fc13(x)) x = F.relu(self.fc14(x)) x_ = torch.add(x, x_) x = self.bn1c(x_) x = F.relu(self.fc15(x)) x = F.relu(self.fc16(x)) x_ = self.fc_down1(torch.add(x, x_)) x = self.bn2a(x_) x = F.relu(self.fc21(x)) x = F.relu(self.fc22(x)) x_ = torch.add(x, x_) x = self.bn2b(x_) x = F.relu(self.fc23(x)) x = F.relu(self.fc24(x)) x_ = torch.add(x, x_) x = self.bn2c(x_) x = F.relu(self.fc25(x)) x = F.relu(self.fc26(x)) x_ = self.fc_down2(torch.add(x, x_)) x = self.bn3a(x_) x = F.relu(self.fc31(x)) x = F.relu(self.fc32(x)) x_ = torch.add(x, x_) x = self.bn3b(x_) x = F.relu(self.fc33(x)) x = F.relu(self.fc34(x)) x_ = torch.add(x, x_) x = self.bn3c(x_) x = F.relu(self.fc35(x)) x = F.relu(self.fc36(x)) x_ = torch.add(x, x_) x = self.fc4(x_) return F.log_softmax(x, dim=1)
29.979381
107
0.532669
import torch import torch.nn as nn import torch.nn.functional as F import torchvision class CustomResnetV1(nn.Module): def __init__(self): super(CustomResnetV1, self).__init__() self.resnet = torchvision.models.resnet18(pretrained=True) self.resnet.conv1 = nn.Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(0, 0), bias=False) self.resnet.fc = nn.Linear(512, 256) self.bn1a = nn.BatchNorm1d(256) self.fc11 = nn.Linear(256, 256) self.fc12 = nn.Linear(256, 256) self.bn1b = nn.BatchNorm1d(256) self.fc13 = nn.Linear(256, 256) self.fc14 = nn.Linear(256, 256) self.bn1c = nn.BatchNorm1d(256) self.fc15 = nn.Linear(256, 256) self.fc16 = nn.Linear(256, 256) self.fc_down1 = nn.Linear(256, 128) self.bn2a = nn.BatchNorm1d(128) self.fc21 = nn.Linear(128, 128) self.fc22 = nn.Linear(128, 128) self.bn2b = nn.BatchNorm1d(128) self.fc23 = nn.Linear(128, 128) self.fc24 = nn.Linear(128, 128) self.bn2c = nn.BatchNorm1d(128) self.fc25 = nn.Linear(128, 128) self.fc26 = nn.Linear(128, 128) self.fc_down2 = nn.Linear(128, 64) self.bn3a = nn.BatchNorm1d(64) self.fc31 = nn.Linear(64, 64) self.fc32 = nn.Linear(64, 64) self.bn3b = nn.BatchNorm1d(64) self.fc33 = nn.Linear(64, 64) self.fc34 = nn.Linear(64, 64) self.bn3c = nn.BatchNorm1d(64) self.fc35 = nn.Linear(64, 64) self.fc36 = nn.Linear(64, 64) self.fc4 = nn.Linear(64, 10) def forward(self, x): x_ = F.relu(self.resnet(x)) x = self.bn1a(x_) x = F.relu(self.fc11(x)) x = F.relu(self.fc12(x)) x_ = torch.add(x, x_) x = self.bn1b(x_) x = F.relu(self.fc13(x)) x = F.relu(self.fc14(x)) x_ = torch.add(x, x_) x = self.bn1c(x_) x = F.relu(self.fc15(x)) x = F.relu(self.fc16(x)) x_ = self.fc_down1(torch.add(x, x_)) x = self.bn2a(x_) x = F.relu(self.fc21(x)) x = F.relu(self.fc22(x)) x_ = torch.add(x, x_) x = self.bn2b(x_) x = F.relu(self.fc23(x)) x = F.relu(self.fc24(x)) x_ = torch.add(x, x_) x = self.bn2c(x_) x = F.relu(self.fc25(x)) x = F.relu(self.fc26(x)) x_ = self.fc_down2(torch.add(x, x_)) x = self.bn3a(x_) x = F.relu(self.fc31(x)) x = F.relu(self.fc32(x)) x_ = torch.add(x, x_) x = self.bn3b(x_) x = F.relu(self.fc33(x)) x = F.relu(self.fc34(x)) x_ = torch.add(x, x_) x = self.bn3c(x_) x = F.relu(self.fc35(x)) x = F.relu(self.fc36(x)) x_ = torch.add(x, x_) x = self.fc4(x_) return F.log_softmax(x, dim=1)
true
true
f7277809d5c13e30181663ab40928852ffba8dea
2,031
py
Python
nyuki/geotiff_reprojector.py
raghuramdr/nyuki
664d3a955ae765214a42e8dbeb009029d5600c15
[ "MIT" ]
null
null
null
nyuki/geotiff_reprojector.py
raghuramdr/nyuki
664d3a955ae765214a42e8dbeb009029d5600c15
[ "MIT" ]
null
null
null
nyuki/geotiff_reprojector.py
raghuramdr/nyuki
664d3a955ae765214a42e8dbeb009029d5600c15
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """Console script for geotiff_reprojector.""" import sys import os import click import rasterio from rasterio.warp import calculate_default_transform, reproject, Resampling def reprojector(sourcefile, target_epsg='EPSG:4326', yes=False): # load file to get epsg info. dat = rasterio.open(sourcefile) # create new target filename targetfile = os.path.basename(sourcefile).split('.')[0] \ + '_proj_' \ + str(target_epsg).split(':')[1] \ + '.tif' click.echo("Application Settings:\n") click.echo(f"source filename: {sourcefile}") click.echo(f"target filename: {targetfile}") click.echo(f"source epsg: {dat.crs}") click.echo(f"target epsg: {target_epsg}\n") dat.close() if not yes: click.confirm('[INFO] File reprojection takes a while.\nDo you want to continue?', abort=True) click.echo('\n[INFO] Good time to get a cup of coffee.\n[INFO] This task can take 15-30 minutes or longer depending on file size.\n') with rasterio.open(sourcefile) as src: transform, width, height = calculate_default_transform( src.crs, target_epsg, src.width, src.height, *src.bounds) kwargs = src.meta.copy() kwargs.update({ 'crs': target_epsg, 'transform': transform, 'width': width, 'height': height, 'compress': 'LZW', 'BIGTIFF' : 'IF_SAFER' }) with rasterio.open(targetfile, 'w', **kwargs) as dst: for i in range(1, src.count + 1): reproject( source=rasterio.band(src, i), destination=rasterio.band(dst, i), src_transform=src.transform, src_crs=src.crs, dst_transform=transform, dst_crs=target_epsg, resampling=Resampling.nearest) click.echo('[INFO] Task complete.') return targetfile
32.758065
141
0.58001
import sys import os import click import rasterio from rasterio.warp import calculate_default_transform, reproject, Resampling def reprojector(sourcefile, target_epsg='EPSG:4326', yes=False): dat = rasterio.open(sourcefile) targetfile = os.path.basename(sourcefile).split('.')[0] \ + '_proj_' \ + str(target_epsg).split(':')[1] \ + '.tif' click.echo("Application Settings:\n") click.echo(f"source filename: {sourcefile}") click.echo(f"target filename: {targetfile}") click.echo(f"source epsg: {dat.crs}") click.echo(f"target epsg: {target_epsg}\n") dat.close() if not yes: click.confirm('[INFO] File reprojection takes a while.\nDo you want to continue?', abort=True) click.echo('\n[INFO] Good time to get a cup of coffee.\n[INFO] This task can take 15-30 minutes or longer depending on file size.\n') with rasterio.open(sourcefile) as src: transform, width, height = calculate_default_transform( src.crs, target_epsg, src.width, src.height, *src.bounds) kwargs = src.meta.copy() kwargs.update({ 'crs': target_epsg, 'transform': transform, 'width': width, 'height': height, 'compress': 'LZW', 'BIGTIFF' : 'IF_SAFER' }) with rasterio.open(targetfile, 'w', **kwargs) as dst: for i in range(1, src.count + 1): reproject( source=rasterio.band(src, i), destination=rasterio.band(dst, i), src_transform=src.transform, src_crs=src.crs, dst_transform=transform, dst_crs=target_epsg, resampling=Resampling.nearest) click.echo('[INFO] Task complete.') return targetfile
true
true
f72779a298c969c64055451d767bd20d007cf308
576
py
Python
django_todos/migrations/0005_list_createdat.py
cxhandley/django-ddp-todos
e752133e31c901aba2ca056d16dc2022c57da823
[ "MIT" ]
2
2015-09-27T13:13:31.000Z
2015-09-28T01:16:11.000Z
django_todos/migrations/0005_list_createdat.py
cxhandley/django-ddp-todos-V2
e752133e31c901aba2ca056d16dc2022c57da823
[ "MIT" ]
null
null
null
django_todos/migrations/0005_list_createdat.py
cxhandley/django-ddp-todos-V2
e752133e31c901aba2ca056d16dc2022c57da823
[ "MIT" ]
1
2015-12-27T15:43:42.000Z
2015-12-27T15:43:42.000Z
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('django_todos', '0004_auto_20150909_1213'), ] operations = [ migrations.AddField( model_name='list', name='createdAt', field=models.DateTimeField(default=datetime.datetime(2015, 9, 14, 11, 27, 52, 487531, tzinfo=utc), auto_now_add=True), preserve_default=False, ), ]
25.043478
130
0.647569
from __future__ import unicode_literals from django.db import models, migrations import datetime from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('django_todos', '0004_auto_20150909_1213'), ] operations = [ migrations.AddField( model_name='list', name='createdAt', field=models.DateTimeField(default=datetime.datetime(2015, 9, 14, 11, 27, 52, 487531, tzinfo=utc), auto_now_add=True), preserve_default=False, ), ]
true
true
f72779dd707f715614f9cebb5334c248393f7004
90
py
Python
03_operator/03_operator.py
Jasper-Li/PythonTutorial
270d18a1830ae74eaa6fc797a6d4f672688f1cee
[ "CC0-1.0" ]
null
null
null
03_operator/03_operator.py
Jasper-Li/PythonTutorial
270d18a1830ae74eaa6fc797a6d4f672688f1cee
[ "CC0-1.0" ]
null
null
null
03_operator/03_operator.py
Jasper-Li/PythonTutorial
270d18a1830ae74eaa6fc797a6d4f672688f1cee
[ "CC0-1.0" ]
null
null
null
# 03 operator print(4+3) print(4-3) print(4*3) print(4 ** 3) # 这个小学没学 print(4/3)
11.25
24
0.566667
print(4+3) print(4-3) print(4*3) print(4 ** 3) print(4/3)
true
true
f7277a1c322b021d0f7590078adba406bb5b75a3
13,460
py
Python
utils/Finger/tool/tools.py
zxpzhong/DR_3DFM
6ef7d0d86813f4cc407a0d1011a2623e4775fbee
[ "MIT" ]
1
2021-01-19T01:44:47.000Z
2021-01-19T01:44:47.000Z
utils/Finger/tool/tools.py
zxpzhong/DR_3DFM
6ef7d0d86813f4cc407a0d1011a2623e4775fbee
[ "MIT" ]
null
null
null
utils/Finger/tool/tools.py
zxpzhong/DR_3DFM
6ef7d0d86813f4cc407a0d1011a2623e4775fbee
[ "MIT" ]
null
null
null
# 定义全局变量和方法 import numpy as np import math # import process.process_finger_data as pfd # 目前选用的图片尺寸 cur_pic_size = [640, 400] # cur_pic_size = [1280, 800] # 相机索引对应相机名称 camera_index_to_name = ['A', 'B', 'C', 'D', 'E', 'F'] # 6个相机的外参 camera_a_outer_para = np.mat([[0.574322111, 0.771054881, 0.275006333, 0.93847817], [0.565423192, -0.130698104, -0.814379899, -0.36935905], [-0.591988790, 0.623211341, -0.511035123, 4.78810628], [0, 0, 0, 1]]) camera_b_outer_para = np.mat([[0.456023570, 0.727006744, 0.513326112, 1.72205846], [-0.146061166, 0.630108915, -0.762645980, -0.30452329], [-0.877900131, 0.272807532, 0.393531969, 5.53092307], [0, 0, 0, 1]]) camera_c_outer_para = np.mat([[0.609183831, 0.528225460, 0.591500569, 1.59956459], [-0.738350101, 0.649953779, 0.179997814, 0.5030131], [-0.289368602, -0.546386263, 0.785956655, 5.58635091], [0, 0, 0, 1]]) camera_d_outer_para = np.mat([[0.771746127, 0.478767298, 0.418556793, 0.955855425], [-0.476877262, 0.000270229651, 0.878969854, 0.477556906], [0.420708915, -0.877941799, 0.228521787, 4.61760675], [0, 0, 0, 1]]) camera_e_outer_para = np.mat([[0.788882832, 0.555210653, 0.263448302, 0.71648894], [0.159053746, -0.598545227, 0.785140445, 0.00777088], [0.593604063, -0.577481378, -0.560490387, 4.30437514], [0, 0, 0, 1]]) camera_f_outer_para = np.mat([[0.712321206, 0.689000523, 0.133704068, 1.13938413], [0.694227260, -0.719684989, 0.0101009224, -0.28640104], [0.103184351, 0.0856259076, -0.990969825, 4.49819911], [0, 0, 0, 1]]) # 六个相机的内参 camera_a_inner_para = np.mat([[967.5377197, 0, 703.1273732, 0], [0, 967.9393921, 351.0187561, 0], [0, 0, 1, 0]]) camera_b_inner_para = np.mat([[963.2991943, 0, 589.8122291, 0], [0, 962.7422485, 412.5244055, 0], [0, 0, 1, 0]]) camera_c_inner_para = np.mat([[967.4086914, 0, 612.7826353, 0], [0, 968.0758667, 451.7366286, 0], [0, 0, 1, 0]]) camera_d_inner_para = np.mat([[961.0868530, 0, 692.7282436, 0], [0, 960.6126708, 417.4375162, 0], [0, 0, 1, 0]]) camera_e_inner_para = np.mat([[955.4882812, 0, 730.3056525, 0], [0, 953.7589722, 451.5117967, 0], [0, 0, 1, 0]]) camera_f_inner_para = np.mat([[962.0779419, 0, 595.2503222, 0], [0, 961.0998535, 396.8389609, 0], [0, 0, 1, 0]]) # 六个相机的投影矩阵为 投影矩阵=内参x外参 # 所有相机的投影矩阵放到一个三维矩阵里(1280x800) all_camera_projection_mat = [ [[1.39434783e+02, 1.18422163e+03, -9.32437833e+01, 4.27466162e+03], [3.39496212e+02, 9.22510264e+01, -9.67653298e+02, 1.32319794e+03], [-5.91988790e-01, 6.23211341e-01, -5.11035123e-01, 4.78810628e+00]], [[-7.85090956e+01, 8.61230229e+02, 7.26596598e+02, 4.92106359e+03], [-5.02774485e+02, 7.19172239e+02, -5.71889964e+02, 1.98846331e+03], [-8.77900131e-01, 2.72807532e-01, 3.93531969e-01, 5.53092307e+00]], [[4.12009678e+02, 1.76193887e+02, 1.05384338e+03, 4.97065152e+03], [-8.45497311e+02, 3.82381880e+02, 5.29296949e+02, 3.01051417e+03], [-2.89368602e-01, -5.46386263e-01, 7.85956655e-01, 5.58635091e+00]], [[1.03315200e+03, -1.48038125e+02, 5.60572927e+02, 4.11740670e+03], [-2.82474656e+02, -3.66226258e+02, 9.39743146e+02, 2.38630951e+03], [4.20708915e-01, -8.77941799e-01, 2.28521787e-01, 4.61760675e+00]], [[1.18728070e+03, 1.08759358e+02, -1.57607533e+02, 3.82810628e+03], [4.19718174e+02, -8.31607535e+02, 4.95766722e+02, 1.95088770e+03], [5.93604063e-01, -5.77481378e-01, -5.60490387e-01, 4.30437514e+00]], [[7.46729038e+02, 7.13841054e+02, -4.61241373e+02, 3.77373081e+03], [7.08169289e+02, -6.57709441e+02, -3.83547441e+02, 1.50980066e+03], [1.03184351e-01, 8.56259076e-02, -9.90969825e-01, 4.49819911e+00]] ] # camera_a_projection_mat = np.mat([[1.39434783e+02, 1.18422163e+03, -9.32437833e+01, 4.27466162e+03], # [3.39496212e+02, 9.22510264e+01, -9.67653298e+02, 1.32319794e+03], # [-5.91988790e-01, 6.23211341e-01, -5.11035123e-01, 4.78810628e+00]]) # # camera_b_projection_mat = np.mat([[-7.85090956e+01, 8.61230229e+02, 7.26596598e+02, 4.92106359e+03], # [-5.02774485e+02, 7.19172239e+02, -5.71889964e+02, 1.98846331e+03], # [-8.77900131e-01, 2.72807532e-01, 3.93531969e-01, 5.53092307e+00]]) # # camera_c_projection_mat = np.mat([[4.12009678e+02, 1.76193887e+02, 1.05384338e+03, 4.97065152e+03], # [-8.45497311e+02, 3.82381880e+02, 5.29296949e+02, 3.01051417e+03], # [-2.89368602e-01, -5.46386263e-01, 7.85956655e-01, 5.58635091e+00]]) # # camera_d_projection_mat = np.mat([[1.03315200e+03, -1.48038125e+02, 5.60572927e+02, 4.11740670e+03], # [-2.82474656e+02, -3.66226258e+02, 9.39743146e+02, 2.38630951e+03], # [4.20708915e-01, -8.77941799e-01, 2.28521787e-01, 4.61760675e+00]]) # # camera_e_projection_mat = np.mat([[1.18728070e+03, 1.08759358e+02, -1.57607533e+02, 3.82810628e+03], # [4.19718174e+02, -8.31607535e+02, 4.95766722e+02, 1.95088770e+03], # [5.93604063e-01, -5.77481378e-01, -5.60490387e-01, 4.30437514e+00]]) # # camera_f_projection_mat = np.mat([[7.46729038e+02, 7.13841054e+02, -4.61241373e+02, 3.77373081e+03], # [7.08169289e+02, -6.57709441e+02, -3.83547441e+02, 1.50980066e+03], # [1.03184351e-01, 8.56259076e-02, -9.90969825e-01, 4.49819911e+00]]) # 将图片缩小为640*400后的相机内参为: 四个参数都除以二 camera_a_inner_para_640_400 = np.mat([[483.76885985, 0, 351.5636866, 0], [0, 483.96969605, 175.50937805, 0], [0, 0, 1, 0]]) camera_b_inner_para_640_400 = np.mat([[481.64959715, 0, 294.90611455, 0], [0, 481.37112425, 206.26220275, 0], [0, 0, 1, 0]]) camera_c_inner_para_640_400 = np.mat([[483.7043457, 0, 306.39131765, 0], [0, 484.03793335, 225.8683143, 0], [0, 0, 1, 0]]) camera_d_inner_para_640_400 = np.mat([[480.5434265, 0, 346.3641218, 0], [0, 480.3063354, 208.7187581, 0], [0, 0, 1, 0]]) camera_e_inner_para_640_400 = np.mat([[477.7441406, 0, 365.15282625, 0], [0, 476.8794861, 225.75589835, 0], [0, 0, 1, 0]]) camera_f_inner_para_640_400 = np.mat([[481.03897095, 0, 297.6251611, 0], [0, 480.54992675, 198.41948045, 0], [0, 0, 1, 0]]) # 将图片resize为640*400后的投影矩阵 all_camera_projection_mat_640_400 = [ [[6.97173914e+01, 5.92110817e+02, - 4.66218917e+01, 2.13733081e+03], [1.69748106e+02, 4.61255132e+01, - 4.83826649e+02, 6.61598968e+02], [-5.91988790e-01, 6.23211341e-01, - 5.11035123e-01, 4.78810628e+00]], [[-3.92545478e+01, 4.30615115e+02, 3.63298299e+02, 2.46053180e+03], [-2.51387243e+02, 3.59586119e+02, - 2.85944982e+02, 9.94231657e+02], [-8.77900131e-01, 2.72807532e-01, 3.93531969e-01, 5.53092307e+00]], [[2.06004839e+02, 8.80969434e+01, 5.26921691e+02, 2.48532576e+03], [-4.22748655e+02, 1.91190940e+02, 2.64648475e+02, 1.50525708e+03], [-2.89368602e-01, - 5.46386263e-01, 7.85956655e-01, 5.58635091e+00]], [[5.16576002e+02, - 7.40190623e+01, 2.80286464e+02, 2.05870335e+03], [-1.41237328e+02, - 1.83113129e+02, 4.69871573e+02, 1.19315475e+03], [4.20708915e-01, - 8.77941799e-01, 2.28521787e-01, 4.61760675e+00]], [[5.93640352e+02, 5.43796790e+01, - 7.88037663e+01, 1.91405314e+03], [2.09859087e+02, - 4.15803768e+02, 2.47883361e+02, 9.75443850e+02], [5.93604063e-01, - 5.77481378e-01, - 5.60490387e-01, 4.30437514e+00]], [[3.73364519e+02, 3.56920527e+02, - 2.30620687e+02, 1.88686540e+03], [3.54084644e+02, - 3.28854721e+02, - 1.91773720e+02, 7.54900332e+02], [1.03184351e-01, 8.56259076e-02, - 9.90969825e-01, 4.49819911e+00]] ] # 六个相机在世界坐标系下的坐标 cameras_coordinate = [[2.50436065, -3.75589484, 1.88800446], [4.02581981, -2.56894275, -3.29281609], [1.01348544, 1.88043939, -5.4273143], [-2.45261002, 3.5962286, -1.87506165], [-3.12155638, 2.09254542, 2.21770186], [-1.07692383, -1.37631717, 4.3081322]] # 六个相机组成的空间平面方程参数 AX+BY+CZ+D=0 camera_plane_para = [19.467678495159983, 18.098947303577706, 10.253452426300939, 1.884526845005233] # 六个相机映射到同一平面后的相机坐标,这里选用的是BCD三个相机作为相机平面,因此只需要将AEF映射到平面 cameras_coordinate_mapping = [[2.45592658, -3.80092362, 1.86249467], [4.02581981, -2.56894275, -3.29281609], [1.01348544, 1.88043939, -5.4273143], [-2.45261002, 3.5962286, -1.87506165], [-3.16297766, 2.05403639, 2.19588564], [-1.08130466, -1.38038999, 4.30582486]] # 六张bmp图片的像素信息,读取后放在全局变量中,避免每次都去重新读取 bmp_pixel = [[], [], [], [], [], []] # 哈希表,存储顶点对应的像素uv信息 map_vertex_to_texture = dict() # 哈希表,存储三角面片顶点对应的vt的index(行数) map_vertex_to_vt_index = dict() # 每个相机对应的三角面片 如faces_belong_camera_A=[[1,3,5],[2,3,5]...] # faces_belong_camera_A = [] # faces_belong_camera_B = [] # faces_belong_camera_C = [] # faces_belong_camera_D = [] # faces_belong_camera_E = [] # faces_belong_camera_F = [] # 所有相机对应的三角面片,A相机放在0索引,以此类推 faces_belong_camera = [[], [], [], [], [], []] # 所有相机对应的bmp应该crop出的范围,[Umin,Vmin,Umax,Vmax],初始化时给相反的最大最小值,这里取的10000和-100,因为不可能有超过这个范围的了 bmp_crop_ranges = [[10000, 10000, -100, -100], [10000, 10000, -100, -100], [10000, 10000, -100, -100], [10000, 10000, -100, -100], [10000, 10000, -100, -100], [10000, 10000, -100, -100]] # 提前计算出crop的宽度u_width和高度v_height,先初始化为0 crops_width_and_height = [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]] # 在得到crops_width_and_height后,提前计算出各个相机crop出的图在png中v所占的范围比重(0-1),例如A:0-0.25,B:0.25-0.4...F:0.8-1 crops_v_scale_in_png = [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]] # uvmap_png的长度和宽度 uv_map_size = [0, 0] # face的索引 寻找bug时使用 face_index = 1 # 打印数据点 def print_data_points(data_points): for li in data_points: print(li) # 计算两个向量的夹角的余弦 # 公式为cos<a,b>=a.b/|a||b|. a.b=(x1x2+y1y2+z1z2) |a|=√(x1^2+y1^2+z1^2), |b|=√(x2^2+y2^2+z2^2). def calculate_cosine(vector1, vector2): a = vector1[0] * vector2[0] + vector1[1] * vector2[1] + vector1[2] * vector2[2] b = math.sqrt(vector1[0] * vector1[0] + vector1[1] * vector1[1] + vector1[2] * vector1[2]) c = math.sqrt(vector2[0] * vector2[0] + vector2[1] * vector2[1] + vector2[2] * vector2[2]) res = a / (b * c) return res # 计算两个向量的向量积 # AB=(x1,y1,z1) CD=(x2,y2,z2) cross(AB,CD)=(y1*z2-y2z1,z1x2-z2x1,x1y2-x2y1) def calculate_vector_product(vector1, vector2): vector_product = [vector1[1] * vector2[2] - vector1[2] * vector2[1], vector1[2] * vector2[0] - vector1[0] * vector2[2], vector1[0] * vector2[1] - vector1[1] * vector2[0]] return vector_product # 点到空间平面的映射点(投影) def get_mapping_point_in_camera_plane(point, camera_plane_para): a = camera_plane_para[0] b = camera_plane_para[1] c = camera_plane_para[2] d = camera_plane_para[3] x = point[0] y = point[1] z = point[2] # 避免重复计算,不知python是否已有优化 a_ = a * a b_ = b * b c_ = c * c temp = a_ + b_ + c_ x_ = ((b_ + c_) * x - a * (b * y + c * z + d)) / temp y_ = ((a_ + c_) * y - b * (a * x + c * z + d)) / temp z_ = ((a_ + b_) * z - c * (a * x + b * y + d)) / temp point_ = [x_, y_, z_] return point_ # # 全局变量中部分数据的由来(在main函数中直接使用了)(因为外参已经固定,所以部分数据基本不会改变,减少计算量) # def pre_process(): # # 求出六个相机在世界坐标系下的坐标 # cameras_coordinate = pfd.get_cameras_coordinate() # # 求出相机参数平面 # camera_plane_para = pfd.get_camera_plane(cameras_coordinate) # # 获取A,E,F的映射点 # camera_a_point = get_mapping_point_in_camera_plane(cameras_coordinate[0], camera_plane_para) # camera_e_point = get_mapping_point_in_camera_plane(cameras_coordinate[4], camera_plane_para) # camera_f_point = get_mapping_point_in_camera_plane(cameras_coordinate[5], camera_plane_para) # # 六个相机归到一个平面之后的坐标:BCD不变,AEF映射到BCD平面 # camera_point_mapping = [camera_a_point, cameras_coordinate[1], cameras_coordinate[2], # cameras_coordinate[3], camera_e_point, camera_f_point] # camera_point_mapping = np.array(camera_point_mapping)
52.784314
104
0.568722
import numpy as np import math cur_pic_size = [640, 400] camera_index_to_name = ['A', 'B', 'C', 'D', 'E', 'F'] camera_a_outer_para = np.mat([[0.574322111, 0.771054881, 0.275006333, 0.93847817], [0.565423192, -0.130698104, -0.814379899, -0.36935905], [-0.591988790, 0.623211341, -0.511035123, 4.78810628], [0, 0, 0, 1]]) camera_b_outer_para = np.mat([[0.456023570, 0.727006744, 0.513326112, 1.72205846], [-0.146061166, 0.630108915, -0.762645980, -0.30452329], [-0.877900131, 0.272807532, 0.393531969, 5.53092307], [0, 0, 0, 1]]) camera_c_outer_para = np.mat([[0.609183831, 0.528225460, 0.591500569, 1.59956459], [-0.738350101, 0.649953779, 0.179997814, 0.5030131], [-0.289368602, -0.546386263, 0.785956655, 5.58635091], [0, 0, 0, 1]]) camera_d_outer_para = np.mat([[0.771746127, 0.478767298, 0.418556793, 0.955855425], [-0.476877262, 0.000270229651, 0.878969854, 0.477556906], [0.420708915, -0.877941799, 0.228521787, 4.61760675], [0, 0, 0, 1]]) camera_e_outer_para = np.mat([[0.788882832, 0.555210653, 0.263448302, 0.71648894], [0.159053746, -0.598545227, 0.785140445, 0.00777088], [0.593604063, -0.577481378, -0.560490387, 4.30437514], [0, 0, 0, 1]]) camera_f_outer_para = np.mat([[0.712321206, 0.689000523, 0.133704068, 1.13938413], [0.694227260, -0.719684989, 0.0101009224, -0.28640104], [0.103184351, 0.0856259076, -0.990969825, 4.49819911], [0, 0, 0, 1]]) camera_a_inner_para = np.mat([[967.5377197, 0, 703.1273732, 0], [0, 967.9393921, 351.0187561, 0], [0, 0, 1, 0]]) camera_b_inner_para = np.mat([[963.2991943, 0, 589.8122291, 0], [0, 962.7422485, 412.5244055, 0], [0, 0, 1, 0]]) camera_c_inner_para = np.mat([[967.4086914, 0, 612.7826353, 0], [0, 968.0758667, 451.7366286, 0], [0, 0, 1, 0]]) camera_d_inner_para = np.mat([[961.0868530, 0, 692.7282436, 0], [0, 960.6126708, 417.4375162, 0], [0, 0, 1, 0]]) camera_e_inner_para = np.mat([[955.4882812, 0, 730.3056525, 0], [0, 953.7589722, 451.5117967, 0], [0, 0, 1, 0]]) camera_f_inner_para = np.mat([[962.0779419, 0, 595.2503222, 0], [0, 961.0998535, 396.8389609, 0], [0, 0, 1, 0]]) all_camera_projection_mat = [ [[1.39434783e+02, 1.18422163e+03, -9.32437833e+01, 4.27466162e+03], [3.39496212e+02, 9.22510264e+01, -9.67653298e+02, 1.32319794e+03], [-5.91988790e-01, 6.23211341e-01, -5.11035123e-01, 4.78810628e+00]], [[-7.85090956e+01, 8.61230229e+02, 7.26596598e+02, 4.92106359e+03], [-5.02774485e+02, 7.19172239e+02, -5.71889964e+02, 1.98846331e+03], [-8.77900131e-01, 2.72807532e-01, 3.93531969e-01, 5.53092307e+00]], [[4.12009678e+02, 1.76193887e+02, 1.05384338e+03, 4.97065152e+03], [-8.45497311e+02, 3.82381880e+02, 5.29296949e+02, 3.01051417e+03], [-2.89368602e-01, -5.46386263e-01, 7.85956655e-01, 5.58635091e+00]], [[1.03315200e+03, -1.48038125e+02, 5.60572927e+02, 4.11740670e+03], [-2.82474656e+02, -3.66226258e+02, 9.39743146e+02, 2.38630951e+03], [4.20708915e-01, -8.77941799e-01, 2.28521787e-01, 4.61760675e+00]], [[1.18728070e+03, 1.08759358e+02, -1.57607533e+02, 3.82810628e+03], [4.19718174e+02, -8.31607535e+02, 4.95766722e+02, 1.95088770e+03], [5.93604063e-01, -5.77481378e-01, -5.60490387e-01, 4.30437514e+00]], [[7.46729038e+02, 7.13841054e+02, -4.61241373e+02, 3.77373081e+03], [7.08169289e+02, -6.57709441e+02, -3.83547441e+02, 1.50980066e+03], [1.03184351e-01, 8.56259076e-02, -9.90969825e-01, 4.49819911e+00]] ] camera_a_inner_para_640_400 = np.mat([[483.76885985, 0, 351.5636866, 0], [0, 483.96969605, 175.50937805, 0], [0, 0, 1, 0]]) camera_b_inner_para_640_400 = np.mat([[481.64959715, 0, 294.90611455, 0], [0, 481.37112425, 206.26220275, 0], [0, 0, 1, 0]]) camera_c_inner_para_640_400 = np.mat([[483.7043457, 0, 306.39131765, 0], [0, 484.03793335, 225.8683143, 0], [0, 0, 1, 0]]) camera_d_inner_para_640_400 = np.mat([[480.5434265, 0, 346.3641218, 0], [0, 480.3063354, 208.7187581, 0], [0, 0, 1, 0]]) camera_e_inner_para_640_400 = np.mat([[477.7441406, 0, 365.15282625, 0], [0, 476.8794861, 225.75589835, 0], [0, 0, 1, 0]]) camera_f_inner_para_640_400 = np.mat([[481.03897095, 0, 297.6251611, 0], [0, 480.54992675, 198.41948045, 0], [0, 0, 1, 0]]) all_camera_projection_mat_640_400 = [ [[6.97173914e+01, 5.92110817e+02, - 4.66218917e+01, 2.13733081e+03], [1.69748106e+02, 4.61255132e+01, - 4.83826649e+02, 6.61598968e+02], [-5.91988790e-01, 6.23211341e-01, - 5.11035123e-01, 4.78810628e+00]], [[-3.92545478e+01, 4.30615115e+02, 3.63298299e+02, 2.46053180e+03], [-2.51387243e+02, 3.59586119e+02, - 2.85944982e+02, 9.94231657e+02], [-8.77900131e-01, 2.72807532e-01, 3.93531969e-01, 5.53092307e+00]], [[2.06004839e+02, 8.80969434e+01, 5.26921691e+02, 2.48532576e+03], [-4.22748655e+02, 1.91190940e+02, 2.64648475e+02, 1.50525708e+03], [-2.89368602e-01, - 5.46386263e-01, 7.85956655e-01, 5.58635091e+00]], [[5.16576002e+02, - 7.40190623e+01, 2.80286464e+02, 2.05870335e+03], [-1.41237328e+02, - 1.83113129e+02, 4.69871573e+02, 1.19315475e+03], [4.20708915e-01, - 8.77941799e-01, 2.28521787e-01, 4.61760675e+00]], [[5.93640352e+02, 5.43796790e+01, - 7.88037663e+01, 1.91405314e+03], [2.09859087e+02, - 4.15803768e+02, 2.47883361e+02, 9.75443850e+02], [5.93604063e-01, - 5.77481378e-01, - 5.60490387e-01, 4.30437514e+00]], [[3.73364519e+02, 3.56920527e+02, - 2.30620687e+02, 1.88686540e+03], [3.54084644e+02, - 3.28854721e+02, - 1.91773720e+02, 7.54900332e+02], [1.03184351e-01, 8.56259076e-02, - 9.90969825e-01, 4.49819911e+00]] ] cameras_coordinate = [[2.50436065, -3.75589484, 1.88800446], [4.02581981, -2.56894275, -3.29281609], [1.01348544, 1.88043939, -5.4273143], [-2.45261002, 3.5962286, -1.87506165], [-3.12155638, 2.09254542, 2.21770186], [-1.07692383, -1.37631717, 4.3081322]] camera_plane_para = [19.467678495159983, 18.098947303577706, 10.253452426300939, 1.884526845005233] cameras_coordinate_mapping = [[2.45592658, -3.80092362, 1.86249467], [4.02581981, -2.56894275, -3.29281609], [1.01348544, 1.88043939, -5.4273143], [-2.45261002, 3.5962286, -1.87506165], [-3.16297766, 2.05403639, 2.19588564], [-1.08130466, -1.38038999, 4.30582486]] bmp_pixel = [[], [], [], [], [], []] map_vertex_to_texture = dict() map_vertex_to_vt_index = dict() faces_belong_camera = [[], [], [], [], [], []] bmp_crop_ranges = [[10000, 10000, -100, -100], [10000, 10000, -100, -100], [10000, 10000, -100, -100], [10000, 10000, -100, -100], [10000, 10000, -100, -100], [10000, 10000, -100, -100]] crops_width_and_height = [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]] crops_v_scale_in_png = [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]] uv_map_size = [0, 0] face_index = 1 def print_data_points(data_points): for li in data_points: print(li) def calculate_cosine(vector1, vector2): a = vector1[0] * vector2[0] + vector1[1] * vector2[1] + vector1[2] * vector2[2] b = math.sqrt(vector1[0] * vector1[0] + vector1[1] * vector1[1] + vector1[2] * vector1[2]) c = math.sqrt(vector2[0] * vector2[0] + vector2[1] * vector2[1] + vector2[2] * vector2[2]) res = a / (b * c) return res def calculate_vector_product(vector1, vector2): vector_product = [vector1[1] * vector2[2] - vector1[2] * vector2[1], vector1[2] * vector2[0] - vector1[0] * vector2[2], vector1[0] * vector2[1] - vector1[1] * vector2[0]] return vector_product def get_mapping_point_in_camera_plane(point, camera_plane_para): a = camera_plane_para[0] b = camera_plane_para[1] c = camera_plane_para[2] d = camera_plane_para[3] x = point[0] y = point[1] z = point[2] a_ = a * a b_ = b * b c_ = c * c temp = a_ + b_ + c_ x_ = ((b_ + c_) * x - a * (b * y + c * z + d)) / temp y_ = ((a_ + c_) * y - b * (a * x + c * z + d)) / temp z_ = ((a_ + b_) * z - c * (a * x + b * y + d)) / temp point_ = [x_, y_, z_] return point_
true
true
f7277b8d58f1c9891a3e5c1152697cdc9322e98f
2,719
py
Python
hdfscm/tests/test_hdfsmanager_api.py
szhem/hdfscm
427e8c85fc70073d9a980e4371804523773545fb
[ "BSD-3-Clause" ]
15
2019-01-14T13:52:02.000Z
2022-02-27T13:40:38.000Z
hdfscm/tests/test_hdfsmanager_api.py
szhem/hdfscm
427e8c85fc70073d9a980e4371804523773545fb
[ "BSD-3-Clause" ]
5
2019-04-09T15:44:38.000Z
2021-04-02T07:01:11.000Z
hdfscm/tests/test_hdfsmanager_api.py
szhem/hdfscm
427e8c85fc70073d9a980e4371804523773545fb
[ "BSD-3-Clause" ]
6
2019-04-15T03:41:08.000Z
2022-03-07T22:48:50.000Z
import nbformat from notebook.services.contents.tests.test_contents_api import ( APITest, assert_http_error ) from traitlets.config import Config from hdfscm import HDFSContentsManager from hdfscm.utils import to_fs_path from .conftest import random_root_dir class HDFSContentsAPITest(APITest): hidden_dirs = [] root_dir = random_root_dir() config = Config() config.NotebookApp.contents_manager_class = HDFSContentsManager config.HDFSContentsManager.root_dir = root_dir @classmethod def setup_class(cls): """Due to https://github.com/docker/for-linux/issues/250, tornado maps localhost to an unresolvable ipv6 address. The easiest way to workaround this is to make it look like python was built without ipv6 support. This patch could fail if `tornado.netutils.bind_sockets` is updated. Note that this doesn't indicate a problem with real world use.""" import socket cls._has_ipv6 = socket.has_ipv6 socket.has_ipv6 = False super().setup_class() @classmethod def teardown_class(cls): """See setUpClass above""" import socket socket.has_ipv6 = cls._has_ipv6 cls.notebook.contents_manager.fs.close() super().teardown_class() def setUp(self): self.notebook.contents_manager.ensure_root_directory() super().setUp() def tearDown(self): super().tearDown() self.fs.delete(self.root_dir, recursive=True) @property def fs(self): return self.notebook.contents_manager.fs def get_hdfs_path(self, api_path): return to_fs_path(api_path, self.root_dir) def make_dir(self, api_path): self.fs.mkdir(self.get_hdfs_path(api_path)) def make_blob(self, api_path, blob): hdfs_path = self.get_hdfs_path(api_path) with self.fs.open(hdfs_path, 'wb') as f: f.write(blob) def make_txt(self, api_path, txt): self.make_blob(api_path, txt.encode('utf-8')) def make_nb(self, api_path, nb): self.make_txt(api_path, nbformat.writes(nb, version=4)) def delete_file(self, api_path): hdfs_path = self.get_hdfs_path(api_path) if self.fs.exists(hdfs_path): self.fs.delete(hdfs_path, recursive=True) delete_dir = delete_file def isfile(self, api_path): return self.fs.isfile(self.get_hdfs_path(api_path)) def isdir(self, api_path): return self.fs.isdir(self.get_hdfs_path(api_path)) # Test overrides. def test_checkpoints_separate_root(self): pass def test_delete_non_empty_dir(self): with assert_http_error(400): self.api.delete('å b') del APITest
29.554348
80
0.681868
import nbformat from notebook.services.contents.tests.test_contents_api import ( APITest, assert_http_error ) from traitlets.config import Config from hdfscm import HDFSContentsManager from hdfscm.utils import to_fs_path from .conftest import random_root_dir class HDFSContentsAPITest(APITest): hidden_dirs = [] root_dir = random_root_dir() config = Config() config.NotebookApp.contents_manager_class = HDFSContentsManager config.HDFSContentsManager.root_dir = root_dir @classmethod def setup_class(cls): import socket cls._has_ipv6 = socket.has_ipv6 socket.has_ipv6 = False super().setup_class() @classmethod def teardown_class(cls): import socket socket.has_ipv6 = cls._has_ipv6 cls.notebook.contents_manager.fs.close() super().teardown_class() def setUp(self): self.notebook.contents_manager.ensure_root_directory() super().setUp() def tearDown(self): super().tearDown() self.fs.delete(self.root_dir, recursive=True) @property def fs(self): return self.notebook.contents_manager.fs def get_hdfs_path(self, api_path): return to_fs_path(api_path, self.root_dir) def make_dir(self, api_path): self.fs.mkdir(self.get_hdfs_path(api_path)) def make_blob(self, api_path, blob): hdfs_path = self.get_hdfs_path(api_path) with self.fs.open(hdfs_path, 'wb') as f: f.write(blob) def make_txt(self, api_path, txt): self.make_blob(api_path, txt.encode('utf-8')) def make_nb(self, api_path, nb): self.make_txt(api_path, nbformat.writes(nb, version=4)) def delete_file(self, api_path): hdfs_path = self.get_hdfs_path(api_path) if self.fs.exists(hdfs_path): self.fs.delete(hdfs_path, recursive=True) delete_dir = delete_file def isfile(self, api_path): return self.fs.isfile(self.get_hdfs_path(api_path)) def isdir(self, api_path): return self.fs.isdir(self.get_hdfs_path(api_path)) def test_checkpoints_separate_root(self): pass def test_delete_non_empty_dir(self): with assert_http_error(400): self.api.delete('å b') del APITest
true
true
f7277cc36cfb1076bc786e7c041456ee46c61223
379
py
Python
setup.py
CesarCaballeroGaudes/phys2denoise
a86baefb62a45721eaa132b1d47fe6c4a0979f35
[ "Apache-2.0" ]
7
2020-06-18T04:31:18.000Z
2022-03-01T14:54:18.000Z
setup.py
CesarCaballeroGaudes/phys2denoise
a86baefb62a45721eaa132b1d47fe6c4a0979f35
[ "Apache-2.0" ]
32
2020-05-01T18:56:11.000Z
2021-08-18T15:09:22.000Z
setup.py
CesarCaballeroGaudes/phys2denoise
a86baefb62a45721eaa132b1d47fe6c4a0979f35
[ "Apache-2.0" ]
10
2020-03-23T11:24:40.000Z
2021-11-22T12:55:06.000Z
#!/usr/bin/env python import sys from setuptools import setup import versioneer SETUP_REQUIRES = ['setuptools >= 30.3.0'] SETUP_REQUIRES += ['wheel'] if 'bdist_wheel' in sys.argv else [] if __name__ == "__main__": setup(name='phys2denoise', setup_requires=SETUP_REQUIRES, version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass())
25.266667
64
0.693931
import sys from setuptools import setup import versioneer SETUP_REQUIRES = ['setuptools >= 30.3.0'] SETUP_REQUIRES += ['wheel'] if 'bdist_wheel' in sys.argv else [] if __name__ == "__main__": setup(name='phys2denoise', setup_requires=SETUP_REQUIRES, version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass())
true
true
f7277cee7021a14d2b5b0b8305bca5e412827cf0
710
py
Python
Timers/timers__.py
nageshnnazare/Python-Advanced-Concepts
cc5aac22799b081abd223c9a7f3c1d5557e3528f
[ "MIT" ]
null
null
null
Timers/timers__.py
nageshnnazare/Python-Advanced-Concepts
cc5aac22799b081abd223c9a7f3c1d5557e3528f
[ "MIT" ]
null
null
null
Timers/timers__.py
nageshnnazare/Python-Advanced-Concepts
cc5aac22799b081abd223c9a7f3c1d5557e3528f
[ "MIT" ]
null
null
null
#Timers # Execute code at timed intervals import time from threading import Timer def display(msg): print(msg + ' ' + time.strftime('%H:%M:%S')) #Basic timer def run_once(): display('Run Once : ') t = Timer(5, display, ['Timeout:']) t.start() run_once() print('Waiting ...') #Interval Timer # Wrap it into class class RepeatTimer(Timer): def run(self): while not self.finished.wait(self.interval): self.function(*self.args, **self.kwargs) print('Done') timer = RepeatTimer(1, display, ['Repeating ']) timer.start() print('Treading Started ') time.sleep(10) # suspend execution print('Threading finished ') timer.cancel()
20.882353
53
0.622535
import time from threading import Timer def display(msg): print(msg + ' ' + time.strftime('%H:%M:%S')) def run_once(): display('Run Once : ') t = Timer(5, display, ['Timeout:']) t.start() run_once() print('Waiting ...') class RepeatTimer(Timer): def run(self): while not self.finished.wait(self.interval): self.function(*self.args, **self.kwargs) print('Done') timer = RepeatTimer(1, display, ['Repeating ']) timer.start() print('Treading Started ') time.sleep(10) print('Threading finished ') timer.cancel()
true
true
f7277e3b484818974b6db28812e583f2b833d7dd
605
py
Python
tests/mock_generator.py
jcheminform/guacamol
dd7f7b12e1ab59151394aba5f4a95ee204fd0203
[ "MIT" ]
242
2018-11-29T13:34:13.000Z
2022-03-26T19:35:17.000Z
tests/mock_generator.py
jcheminform/guacamol
dd7f7b12e1ab59151394aba5f4a95ee204fd0203
[ "MIT" ]
13
2019-01-31T03:33:36.000Z
2022-01-03T07:03:19.000Z
tests/mock_generator.py
jcheminform/guacamol
dd7f7b12e1ab59151394aba5f4a95ee204fd0203
[ "MIT" ]
68
2018-11-26T10:03:41.000Z
2022-03-28T20:58:20.000Z
from typing import List from guacamol.distribution_matching_generator import DistributionMatchingGenerator class MockGenerator(DistributionMatchingGenerator): """ Mock generator that returns pre-defined molecules, possibly split in several calls """ def __init__(self, molecules: List[str]) -> None: self.molecules = molecules self.cursor = 0 def generate(self, number_samples: int) -> List[str]: end = self.cursor + number_samples sampled_molecules = self.molecules[self.cursor:end] self.cursor = end return sampled_molecules
27.5
82
0.707438
from typing import List from guacamol.distribution_matching_generator import DistributionMatchingGenerator class MockGenerator(DistributionMatchingGenerator): def __init__(self, molecules: List[str]) -> None: self.molecules = molecules self.cursor = 0 def generate(self, number_samples: int) -> List[str]: end = self.cursor + number_samples sampled_molecules = self.molecules[self.cursor:end] self.cursor = end return sampled_molecules
true
true
f7277ef92647633965a12e98c00211e924095a71
158
py
Python
03_Estrutura_de_Repeticao/12_gerador_tabuada.py
gabrieldcpadilha/ListaDeExercicios-PythonBrasil
a92d477468bde5eac8987a26ea79af2ffeb6ad81
[ "MIT" ]
null
null
null
03_Estrutura_de_Repeticao/12_gerador_tabuada.py
gabrieldcpadilha/ListaDeExercicios-PythonBrasil
a92d477468bde5eac8987a26ea79af2ffeb6ad81
[ "MIT" ]
10
2020-08-19T04:31:52.000Z
2020-09-21T22:48:29.000Z
03_Estrutura_de_Repeticao/12_gerador_tabuada.py
gabrieldcpadilha/ListaDeExercicios-PythonBrasil
a92d477468bde5eac8987a26ea79af2ffeb6ad81
[ "MIT" ]
null
null
null
num = int(input('Informe o numero que voce deseja ver a tabuada: ')) print(f'Tabuada de {num}') for c in range(0, 11): print(f'{num} X {c} = {num * c}')
26.333333
68
0.607595
num = int(input('Informe o numero que voce deseja ver a tabuada: ')) print(f'Tabuada de {num}') for c in range(0, 11): print(f'{num} X {c} = {num * c}')
true
true
f7277f4bc851f4bcbda0ff622dd70c2d8c114bb2
398
py
Python
tgBCoinBot/wsgi.py
steveyout/bitc
3fb227ba35d0daa8c2337cf8761cf68a752a973d
[ "Apache-2.0" ]
1
2021-01-30T10:25:04.000Z
2021-01-30T10:25:04.000Z
tgBCoinBot/wsgi.py
steveyout/pyth
d7178c76fa1a110c3d95df48bbec555b68dad618
[ "Apache-2.0" ]
2
2020-02-12T01:28:33.000Z
2020-06-05T18:52:39.000Z
tgBCoinBot/wsgi.py
steveyout/bitc
3fb227ba35d0daa8c2337cf8761cf68a752a973d
[ "Apache-2.0" ]
null
null
null
""" WSGI config for tgBCoinBot project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tgBCoinBot.settings") application = get_wsgi_application()
23.411765
78
0.788945
import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tgBCoinBot.settings") application = get_wsgi_application()
true
true
f7277fcf10b974b66303d90351215882cab6362f
3,232
py
Python
venv/lib/python2.7/site-packages/test/test_wsgi.py
sravani-m/Web-Application-Security-Framework
d9f71538f5cba6fe1d8eabcb26c557565472f6a6
[ "MIT" ]
3
2019-04-09T22:59:33.000Z
2019-06-14T09:23:24.000Z
venv/lib/python2.7/site-packages/test/test_wsgi.py
sravani-m/Web-Application-Security-Framework
d9f71538f5cba6fe1d8eabcb26c557565472f6a6
[ "MIT" ]
null
null
null
venv/lib/python2.7/site-packages/test/test_wsgi.py
sravani-m/Web-Application-Security-Framework
d9f71538f5cba6fe1d8eabcb26c557565472f6a6
[ "MIT" ]
null
null
null
import cStringIO import sys from netlib import wsgi, odict def tflow(): h = odict.ODictCaseless() h["test"] = ["value"] req = wsgi.Request("http", "GET", "/", h, "") return wsgi.Flow(("127.0.0.1", 8888), req) class TestApp: def __init__(self): self.called = False def __call__(self, environ, start_response): self.called = True status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) return ['Hello', ' world!\n'] class TestWSGI: def test_make_environ(self): w = wsgi.WSGIAdaptor(None, "foo", 80, "version") tf = tflow() assert w.make_environ(tf, None) tf.request.path = "/foo?bar=voing" r = w.make_environ(tf, None) assert r["QUERY_STRING"] == "bar=voing" def test_serve(self): ta = TestApp() w = wsgi.WSGIAdaptor(ta, "foo", 80, "version") f = tflow() f.request.host = "foo" f.request.port = 80 wfile = cStringIO.StringIO() err = w.serve(f, wfile) assert ta.called assert not err val = wfile.getvalue() assert "Hello world" in val assert "Server:" in val def _serve(self, app): w = wsgi.WSGIAdaptor(app, "foo", 80, "version") f = tflow() f.request.host = "foo" f.request.port = 80 wfile = cStringIO.StringIO() w.serve(f, wfile) return wfile.getvalue() def test_serve_empty_body(self): def app(environ, start_response): status = '200 OK' response_headers = [('Foo', 'bar')] start_response(status, response_headers) return [] assert self._serve(app) def test_serve_double_start(self): def app(environ, start_response): try: raise ValueError("foo") except: sys.exc_info() status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) start_response(status, response_headers) assert "Internal Server Error" in self._serve(app) def test_serve_single_err(self): def app(environ, start_response): try: raise ValueError("foo") except: ei = sys.exc_info() status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers, ei) assert "Internal Server Error" in self._serve(app) def test_serve_double_err(self): def app(environ, start_response): try: raise ValueError("foo") except: ei = sys.exc_info() status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) yield "aaa" start_response(status, response_headers, ei) yield "bbb" assert "Internal Server Error" in self._serve(app)
30.490566
64
0.537438
import cStringIO import sys from netlib import wsgi, odict def tflow(): h = odict.ODictCaseless() h["test"] = ["value"] req = wsgi.Request("http", "GET", "/", h, "") return wsgi.Flow(("127.0.0.1", 8888), req) class TestApp: def __init__(self): self.called = False def __call__(self, environ, start_response): self.called = True status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) return ['Hello', ' world!\n'] class TestWSGI: def test_make_environ(self): w = wsgi.WSGIAdaptor(None, "foo", 80, "version") tf = tflow() assert w.make_environ(tf, None) tf.request.path = "/foo?bar=voing" r = w.make_environ(tf, None) assert r["QUERY_STRING"] == "bar=voing" def test_serve(self): ta = TestApp() w = wsgi.WSGIAdaptor(ta, "foo", 80, "version") f = tflow() f.request.host = "foo" f.request.port = 80 wfile = cStringIO.StringIO() err = w.serve(f, wfile) assert ta.called assert not err val = wfile.getvalue() assert "Hello world" in val assert "Server:" in val def _serve(self, app): w = wsgi.WSGIAdaptor(app, "foo", 80, "version") f = tflow() f.request.host = "foo" f.request.port = 80 wfile = cStringIO.StringIO() w.serve(f, wfile) return wfile.getvalue() def test_serve_empty_body(self): def app(environ, start_response): status = '200 OK' response_headers = [('Foo', 'bar')] start_response(status, response_headers) return [] assert self._serve(app) def test_serve_double_start(self): def app(environ, start_response): try: raise ValueError("foo") except: sys.exc_info() status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) start_response(status, response_headers) assert "Internal Server Error" in self._serve(app) def test_serve_single_err(self): def app(environ, start_response): try: raise ValueError("foo") except: ei = sys.exc_info() status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers, ei) assert "Internal Server Error" in self._serve(app) def test_serve_double_err(self): def app(environ, start_response): try: raise ValueError("foo") except: ei = sys.exc_info() status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) yield "aaa" start_response(status, response_headers, ei) yield "bbb" assert "Internal Server Error" in self._serve(app)
true
true
f7277fd31391e322ececec43a17017d86e45c1ec
10,296
py
Python
train.py
jojotenya/LAMOL
03c31d9f0c7bf71295bc2d362ddf40a7656956e1
[ "MIT" ]
75
2019-12-22T18:59:05.000Z
2021-09-17T06:30:38.000Z
train.py
chho33/LAMOL
03c31d9f0c7bf71295bc2d362ddf40a7656956e1
[ "MIT" ]
5
2020-05-03T10:00:05.000Z
2021-08-04T05:35:57.000Z
train.py
jojotenya/LAMOL
03c31d9f0c7bf71295bc2d362ddf40a7656956e1
[ "MIT" ]
9
2020-02-14T17:33:58.000Z
2021-06-08T06:02:13.000Z
import torch from torch.utils.data import DataLoader from torch import nn from pytorch_transformers import AdamW, WEIGHTS_NAME, WarmupLinearSchedule import csv import numpy as np import os import logging from fp16 import FP16_Module, FP16_Optimizer from parallel import DataParallelModel, DataParallelCriterion from collections import OrderedDict from utils import * from settings import args, TASK_DICT, init_logging, MODEL_CONFIG, MODEL_CLASS, SPECIAL_TOKENS, CONFIG_CLASS from settings import TOKENIZER, SPECIAL_TOKEN_IDS, FILL_VAL, SAVE_NAME, FINAL_SAVE_NAME, TOKENS_WEIGHT, CONFIG_NAME from scheduler import AnnealingLR from regularizers import REG_TYPES, REG_TYPE_KEYS, Weight_Regularized_AdamW, Weight_Regularized_SGD from torch.nn import CrossEntropyLoss logger = logging.getLogger(__name__) def train(task_ids, model): tasks = [args.tasks[task_id] for task_id in task_ids] logger.info("start to train { task: %s, seq train type: %s }" % (tasks, args.seq_train_type)) model_dir = get_model_dir(tasks) make_dir(model_dir) train_dataset = [TASK_DICT[t]["train"] for t in tasks] train_extra_data = [] if "lll" in args.seq_train_type and task_ids[0] > 0 and not args.skip_tasks: prev_task = args.tasks[task_ids[0]-1] with torch.no_grad(): create_extra_data(tasks[0], prev_task, model, train_extra_data) elif "gem" in args.seq_train_type and task_ids[0] > 0: get_real_data(tasks[0], train_extra_data, accum=False, encode=True) args.memory_data.append(train_extra_data) train_extra_data = [] logger.info('extra training data size: {}'.format(len(train_extra_data))) if not model: # which_model_to_load = model_dir if os.path.isfile(os.path.join(model_dir, FINAL_SAVE_NAME)) else args.model_name model = MODEL_CLASS.from_pretrained(args.model_name).cuda() model.resize_token_embeddings(len(TOKENIZER)) if not args.fp32: model = FP16_Module(model) gen_token = get_gen_token(tasks[0]) TOKENIZER.add_tokens([gen_token]) TOKENIZER.save_pretrained(model_dir) SPECIAL_TOKENS[tasks[0]] = gen_token SPECIAL_TOKEN_IDS[tasks[0]] = TOKENIZER.convert_tokens_to_ids(gen_token) logger.info('gen token = {} , gen token id = {}'.format(gen_token, SPECIAL_TOKEN_IDS[tasks[0]])) MODEL_CONFIG.vocab_size = len(TOKENIZER) MODEL_CONFIG.to_json_file(os.path.join(model_dir,CONFIG_NAME)) global TOKENS_WEIGHT if len(TOKENIZER) != TOKENS_WEIGHT.shape[0]: TOKENS_WEIGHT = torch.cat((TOKENS_WEIGHT, torch.ones([1]).cuda())) if args.skip_tasks and len(tasks) == 1: logger.info("*********** skip task: {} ***********".format(tasks[0])) if tasks[0] in args.skip_tasks: if len(args.skip_tasks) == 1: model_dir = get_model_dir(tasks) model_path = os.path.join(model_dir, FINAL_SAVE_NAME) config_path = os.path.join(model_dir,CONFIG_NAME) model_config = CONFIG_CLASS.from_json_file(config_path) model = MODEL_CLASS(model_config).cuda() state_dict = torch.load(model_path) model.load_state_dict(state_dict) if not args.fp32: model = FP16_Module(model) if args.seq_train_type in REG_TYPE_KEYS: logger.info("calulating reg_params ...") train_qadata = QADataset(train_dataset, "train", SPECIAL_TOKEN_IDS[tasks[0]], train_extra_data) max_train_batch_size = max(len(train_qadata) // args.min_n_steps, args.min_batch_size) train_dataloader = create_dataloader(train_qadata, "train", max_train_batch_size) parallel_model = DataParallelModel(WrapModel(model), args.device_ids) regularizer = REG_TYPES[args.seq_train_type](model, parallel_model, [train_dataloader], tasks[0]) regularizer.task_start_do() regularizer.task_end_do() torch.save(model.state_dict(), os.path.join(model_dir, FINAL_SAVE_NAME)) logger.info("done reg_params!") args.skip_tasks.remove(tasks[0]) return model model.resize_token_embeddings(len(TOKENIZER)) if not args.fp32: # again because resize_token_embeddings makes embedding layer fp32 model = FP16_Module(model) parallel_model = DataParallelModel(WrapModel(model), args.device_ids) train_qadata = QADataset(train_dataset, "train", SPECIAL_TOKEN_IDS[tasks[0]], train_extra_data) max_train_batch_size = max(len(train_qadata) // args.min_n_steps, args.min_batch_size) train_dataloader = create_dataloader(train_qadata, "train", max_train_batch_size) if not args.unbound and args.seq_train_type != "multitask": #n_train_epochs = TASK_DICT[tasks[0]]["n_train_epochs"] n_train_epochs = args.n_train_epochs[tasks[0]] else: n_train_epochs = args.n_train_epochs['_'.join(tasks)] n_train_optimization_steps = len(train_qadata) * n_train_epochs logger.info('len of train dataset: {} , max train batch size {} , num of opt steps: {}'.format( len(train_qadata), max_train_batch_size, n_train_optimization_steps)) param_optimizer = list(model.named_parameters()) no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': args.weight_decay}, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0} ] if "gem" in args.seq_train_type: model.task_id = task_ids[0] if not hasattr(model, "grad_dims"): model.grad_dims = [] for param in model.parameters(): model.grad_dims.append(param.data.numel()) if not hasattr(model, "grads"): model.grads = torch.zeros(sum(model.grad_dims),len(args.tasks)) model.grads = model.grads.cuda() if args.seq_train_type in REG_TYPE_KEYS: optimizer = Weight_Regularized_AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon) else: optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon) if not args.fp32: optimizer = FP16_Optimizer(optimizer, static_loss_scale=None, dynamic_loss_scale=True, dynamic_loss_args={'scale_window': 100, 'min_scale': 1, 'delayed_shift': 2}) scheduler = AnnealingLR(optimizer, start_lr=args.learning_rate, warmup_iter=int(args.n_warmup_ratio*len(train_qadata)), num_iters=int(n_train_optimization_steps), decay_style=args.decay_style) train_loss_fct = DataParallelCriterion(CrossEntropyLoss(ignore_index=FILL_VAL, weight=TOKENS_WEIGHT), args.device_ids) if args.seq_train_type in REG_TYPE_KEYS: copy_train_dataloader = create_dataloader(train_qadata, "train", max_train_batch_size) prev_task = args.tasks[task_ids[0]-1] regularizer = REG_TYPES[args.seq_train_type](model, parallel_model, [copy_train_dataloader], tasks[0], prev_task) regularizer.task_start_do() tot_n_steps = 0 train_once = TrainStep(model, optimizer, scheduler) if "gem" in args.seq_train_type and task_ids[0] != 0: gem_step = GEMStep(model, parallel_model, train_loss_fct, optimizer) model.train() for ep in range(n_train_epochs): cum_loss, cum_qa_loss, cum_lm_loss, cur_n_inputs = 0, 0, 0, 0 for n_steps, (_, _, cqa, _, Y, gen_X, gen_Y) in enumerate(train_dataloader): n_inputs = sum(_cqa.shape[0] for _cqa in cqa) for i in range(len(cqa)): cqa[i] = (cqa[i].to(args.device_ids[i]),) Y[i] = Y[i].to(args.device_ids[i]) gen_X[i] = (gen_X[i].to(args.device_ids[i]),) gen_Y[i] = gen_Y[i].to(args.device_ids[i]) losses = get_losses(parallel_model, cqa, Y, gen_X, gen_Y, train_loss_fct) loss = sum(losses) if "gem" in args.seq_train_type and task_ids[0] != 0: gem_step(task_ids[0]) train_once(loss, n_inputs) qa_loss = losses[0].item() * n_inputs lm_loss = losses[1].item() * n_inputs cum_loss += (qa_loss + lm_loss) cum_qa_loss += qa_loss cum_lm_loss += lm_loss cur_n_inputs += n_inputs if (n_steps + 1 ) % args.logging_steps == 0: logger.info('progress {:.3f} , lr {:.1E} , loss {:.3f} , qa loss {:.3f} , lm loss {:.3f} , avg batch size {:.1f}'.format( ep + cur_n_inputs/len(train_qadata), scheduler.get_lr(), cum_loss/cur_n_inputs, cum_qa_loss/cur_n_inputs, cum_lm_loss/cur_n_inputs, cur_n_inputs/(n_steps + 1) )) torch.save(model.state_dict(), os.path.join(model_dir, SAVE_NAME+str(ep+1))) tot_n_steps += (n_steps + 1) logger.info('epoch {}/{} done , tot steps {} , lr {:.1E} , loss {:.2f} , qa loss {:.2f} , lm loss {:.2f} , avg batch size {:.1f}'.format( ep+1, n_train_epochs, tot_n_steps, scheduler.get_lr(), cum_loss/cur_n_inputs, cum_qa_loss/cur_n_inputs, cum_lm_loss/cur_n_inputs, cur_n_inputs/(n_steps+1) )) # task end do for reg if args.seq_train_type in REG_TYPE_KEYS: regularizer.task_end_do() torch.save(model.state_dict(), os.path.join(model_dir, FINAL_SAVE_NAME)) return model if __name__ == '__main__': if not args.debug: logging.getLogger("pytorch_transformers").setLevel(logging.WARNING) logging.getLogger("pytorch_transformers.tokenization_utils").setLevel(logging.CRITICAL) make_dir(args.model_dir_root) init_logging(os.path.join(args.model_dir_root, 'log_train.txt')) logger.info('args = {}'.format(str(args))) model = None if args.seq_train_type == "multitask": model = train(list(range(len(args.tasks))), model) else: if args.unbound: TASK_DICT = lll_unbound_setting(split_size=args.unbound) for task_id in range(len(args.tasks)): model = train([task_id], model)
49.263158
166
0.668512
import torch from torch.utils.data import DataLoader from torch import nn from pytorch_transformers import AdamW, WEIGHTS_NAME, WarmupLinearSchedule import csv import numpy as np import os import logging from fp16 import FP16_Module, FP16_Optimizer from parallel import DataParallelModel, DataParallelCriterion from collections import OrderedDict from utils import * from settings import args, TASK_DICT, init_logging, MODEL_CONFIG, MODEL_CLASS, SPECIAL_TOKENS, CONFIG_CLASS from settings import TOKENIZER, SPECIAL_TOKEN_IDS, FILL_VAL, SAVE_NAME, FINAL_SAVE_NAME, TOKENS_WEIGHT, CONFIG_NAME from scheduler import AnnealingLR from regularizers import REG_TYPES, REG_TYPE_KEYS, Weight_Regularized_AdamW, Weight_Regularized_SGD from torch.nn import CrossEntropyLoss logger = logging.getLogger(__name__) def train(task_ids, model): tasks = [args.tasks[task_id] for task_id in task_ids] logger.info("start to train { task: %s, seq train type: %s }" % (tasks, args.seq_train_type)) model_dir = get_model_dir(tasks) make_dir(model_dir) train_dataset = [TASK_DICT[t]["train"] for t in tasks] train_extra_data = [] if "lll" in args.seq_train_type and task_ids[0] > 0 and not args.skip_tasks: prev_task = args.tasks[task_ids[0]-1] with torch.no_grad(): create_extra_data(tasks[0], prev_task, model, train_extra_data) elif "gem" in args.seq_train_type and task_ids[0] > 0: get_real_data(tasks[0], train_extra_data, accum=False, encode=True) args.memory_data.append(train_extra_data) train_extra_data = [] logger.info('extra training data size: {}'.format(len(train_extra_data))) if not model: model = MODEL_CLASS.from_pretrained(args.model_name).cuda() model.resize_token_embeddings(len(TOKENIZER)) if not args.fp32: model = FP16_Module(model) gen_token = get_gen_token(tasks[0]) TOKENIZER.add_tokens([gen_token]) TOKENIZER.save_pretrained(model_dir) SPECIAL_TOKENS[tasks[0]] = gen_token SPECIAL_TOKEN_IDS[tasks[0]] = TOKENIZER.convert_tokens_to_ids(gen_token) logger.info('gen token = {} , gen token id = {}'.format(gen_token, SPECIAL_TOKEN_IDS[tasks[0]])) MODEL_CONFIG.vocab_size = len(TOKENIZER) MODEL_CONFIG.to_json_file(os.path.join(model_dir,CONFIG_NAME)) global TOKENS_WEIGHT if len(TOKENIZER) != TOKENS_WEIGHT.shape[0]: TOKENS_WEIGHT = torch.cat((TOKENS_WEIGHT, torch.ones([1]).cuda())) if args.skip_tasks and len(tasks) == 1: logger.info("*********** skip task: {} ***********".format(tasks[0])) if tasks[0] in args.skip_tasks: if len(args.skip_tasks) == 1: model_dir = get_model_dir(tasks) model_path = os.path.join(model_dir, FINAL_SAVE_NAME) config_path = os.path.join(model_dir,CONFIG_NAME) model_config = CONFIG_CLASS.from_json_file(config_path) model = MODEL_CLASS(model_config).cuda() state_dict = torch.load(model_path) model.load_state_dict(state_dict) if not args.fp32: model = FP16_Module(model) if args.seq_train_type in REG_TYPE_KEYS: logger.info("calulating reg_params ...") train_qadata = QADataset(train_dataset, "train", SPECIAL_TOKEN_IDS[tasks[0]], train_extra_data) max_train_batch_size = max(len(train_qadata) // args.min_n_steps, args.min_batch_size) train_dataloader = create_dataloader(train_qadata, "train", max_train_batch_size) parallel_model = DataParallelModel(WrapModel(model), args.device_ids) regularizer = REG_TYPES[args.seq_train_type](model, parallel_model, [train_dataloader], tasks[0]) regularizer.task_start_do() regularizer.task_end_do() torch.save(model.state_dict(), os.path.join(model_dir, FINAL_SAVE_NAME)) logger.info("done reg_params!") args.skip_tasks.remove(tasks[0]) return model model.resize_token_embeddings(len(TOKENIZER)) if not args.fp32: model = FP16_Module(model) parallel_model = DataParallelModel(WrapModel(model), args.device_ids) train_qadata = QADataset(train_dataset, "train", SPECIAL_TOKEN_IDS[tasks[0]], train_extra_data) max_train_batch_size = max(len(train_qadata) // args.min_n_steps, args.min_batch_size) train_dataloader = create_dataloader(train_qadata, "train", max_train_batch_size) if not args.unbound and args.seq_train_type != "multitask": n_train_epochs = args.n_train_epochs[tasks[0]] else: n_train_epochs = args.n_train_epochs['_'.join(tasks)] n_train_optimization_steps = len(train_qadata) * n_train_epochs logger.info('len of train dataset: {} , max train batch size {} , num of opt steps: {}'.format( len(train_qadata), max_train_batch_size, n_train_optimization_steps)) param_optimizer = list(model.named_parameters()) no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': args.weight_decay}, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0} ] if "gem" in args.seq_train_type: model.task_id = task_ids[0] if not hasattr(model, "grad_dims"): model.grad_dims = [] for param in model.parameters(): model.grad_dims.append(param.data.numel()) if not hasattr(model, "grads"): model.grads = torch.zeros(sum(model.grad_dims),len(args.tasks)) model.grads = model.grads.cuda() if args.seq_train_type in REG_TYPE_KEYS: optimizer = Weight_Regularized_AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon) else: optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon) if not args.fp32: optimizer = FP16_Optimizer(optimizer, static_loss_scale=None, dynamic_loss_scale=True, dynamic_loss_args={'scale_window': 100, 'min_scale': 1, 'delayed_shift': 2}) scheduler = AnnealingLR(optimizer, start_lr=args.learning_rate, warmup_iter=int(args.n_warmup_ratio*len(train_qadata)), num_iters=int(n_train_optimization_steps), decay_style=args.decay_style) train_loss_fct = DataParallelCriterion(CrossEntropyLoss(ignore_index=FILL_VAL, weight=TOKENS_WEIGHT), args.device_ids) if args.seq_train_type in REG_TYPE_KEYS: copy_train_dataloader = create_dataloader(train_qadata, "train", max_train_batch_size) prev_task = args.tasks[task_ids[0]-1] regularizer = REG_TYPES[args.seq_train_type](model, parallel_model, [copy_train_dataloader], tasks[0], prev_task) regularizer.task_start_do() tot_n_steps = 0 train_once = TrainStep(model, optimizer, scheduler) if "gem" in args.seq_train_type and task_ids[0] != 0: gem_step = GEMStep(model, parallel_model, train_loss_fct, optimizer) model.train() for ep in range(n_train_epochs): cum_loss, cum_qa_loss, cum_lm_loss, cur_n_inputs = 0, 0, 0, 0 for n_steps, (_, _, cqa, _, Y, gen_X, gen_Y) in enumerate(train_dataloader): n_inputs = sum(_cqa.shape[0] for _cqa in cqa) for i in range(len(cqa)): cqa[i] = (cqa[i].to(args.device_ids[i]),) Y[i] = Y[i].to(args.device_ids[i]) gen_X[i] = (gen_X[i].to(args.device_ids[i]),) gen_Y[i] = gen_Y[i].to(args.device_ids[i]) losses = get_losses(parallel_model, cqa, Y, gen_X, gen_Y, train_loss_fct) loss = sum(losses) if "gem" in args.seq_train_type and task_ids[0] != 0: gem_step(task_ids[0]) train_once(loss, n_inputs) qa_loss = losses[0].item() * n_inputs lm_loss = losses[1].item() * n_inputs cum_loss += (qa_loss + lm_loss) cum_qa_loss += qa_loss cum_lm_loss += lm_loss cur_n_inputs += n_inputs if (n_steps + 1 ) % args.logging_steps == 0: logger.info('progress {:.3f} , lr {:.1E} , loss {:.3f} , qa loss {:.3f} , lm loss {:.3f} , avg batch size {:.1f}'.format( ep + cur_n_inputs/len(train_qadata), scheduler.get_lr(), cum_loss/cur_n_inputs, cum_qa_loss/cur_n_inputs, cum_lm_loss/cur_n_inputs, cur_n_inputs/(n_steps + 1) )) torch.save(model.state_dict(), os.path.join(model_dir, SAVE_NAME+str(ep+1))) tot_n_steps += (n_steps + 1) logger.info('epoch {}/{} done , tot steps {} , lr {:.1E} , loss {:.2f} , qa loss {:.2f} , lm loss {:.2f} , avg batch size {:.1f}'.format( ep+1, n_train_epochs, tot_n_steps, scheduler.get_lr(), cum_loss/cur_n_inputs, cum_qa_loss/cur_n_inputs, cum_lm_loss/cur_n_inputs, cur_n_inputs/(n_steps+1) )) if args.seq_train_type in REG_TYPE_KEYS: regularizer.task_end_do() torch.save(model.state_dict(), os.path.join(model_dir, FINAL_SAVE_NAME)) return model if __name__ == '__main__': if not args.debug: logging.getLogger("pytorch_transformers").setLevel(logging.WARNING) logging.getLogger("pytorch_transformers.tokenization_utils").setLevel(logging.CRITICAL) make_dir(args.model_dir_root) init_logging(os.path.join(args.model_dir_root, 'log_train.txt')) logger.info('args = {}'.format(str(args))) model = None if args.seq_train_type == "multitask": model = train(list(range(len(args.tasks))), model) else: if args.unbound: TASK_DICT = lll_unbound_setting(split_size=args.unbound) for task_id in range(len(args.tasks)): model = train([task_id], model)
true
true
f7278004acfca10614fa1c33b678146eff3e8f86
1,850
py
Python
scikit-learn-weighted_kde/examples/svm/plot_separating_hyperplane_unbalanced.py
RTHMaK/git-squash-master
76c4c8437dd18114968e69a698f4581927fcdabf
[ "BSD-2-Clause" ]
1
2021-11-26T12:22:13.000Z
2021-11-26T12:22:13.000Z
scikit-learn-weighted_kde/examples/svm/plot_separating_hyperplane_unbalanced.py
RTHMaK/git-squash-master
76c4c8437dd18114968e69a698f4581927fcdabf
[ "BSD-2-Clause" ]
null
null
null
scikit-learn-weighted_kde/examples/svm/plot_separating_hyperplane_unbalanced.py
RTHMaK/git-squash-master
76c4c8437dd18114968e69a698f4581927fcdabf
[ "BSD-2-Clause" ]
null
null
null
""" ================================================= SVM: Separating hyperplane for unbalanced classes ================================================= Find the optimal separating hyperplane using an SVC for classes that are unbalanced. We first find the separating plane with a plain SVC and then plot (dashed) the separating hyperplane with automatically correction for unbalanced classes. .. currentmodule:: sklearn.linear_model .. note:: This example will also work by replacing ``SVC(kernel="linear")`` with ``SGDClassifier(loss="hinge")``. Setting the ``loss`` parameter of the :class:`SGDClassifier` equal to ``hinge`` will yield behaviour such as that of a SVC with a linear kernel. For example try instead of the ``SVC``:: clf = SGDClassifier(n_iter=100, alpha=0.01) """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import svm #from sklearn.linear_model import SGDClassifier # we create 40 separable points rng = np.random.RandomState(0) n_samples_1 = 1000 n_samples_2 = 100 X = np.r_[1.5 * rng.randn(n_samples_1, 2), 0.5 * rng.randn(n_samples_2, 2) + [2, 2]] y = [0] * (n_samples_1) + [1] * (n_samples_2) # fit the model and get the separating hyperplane clf = svm.SVC(kernel='linear', C=1.0) clf.fit(X, y) w = clf.coef_[0] a = -w[0] / w[1] xx = np.linspace(-5, 5) yy = a * xx - clf.intercept_[0] / w[1] # get the separating hyperplane using weighted classes wclf = svm.SVC(kernel='linear', class_weight={1: 10}) wclf.fit(X, y) ww = wclf.coef_[0] wa = -ww[0] / ww[1] wyy = wa * xx - wclf.intercept_[0] / ww[1] # plot separating hyperplanes and samples h0 = plt.plot(xx, yy, 'k-', label='no weights') h1 = plt.plot(xx, wyy, 'k--', label='with weights') plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired) plt.legend() plt.axis('tight') plt.show()
27.205882
73
0.651351
print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import svm rng = np.random.RandomState(0) n_samples_1 = 1000 n_samples_2 = 100 X = np.r_[1.5 * rng.randn(n_samples_1, 2), 0.5 * rng.randn(n_samples_2, 2) + [2, 2]] y = [0] * (n_samples_1) + [1] * (n_samples_2) clf = svm.SVC(kernel='linear', C=1.0) clf.fit(X, y) w = clf.coef_[0] a = -w[0] / w[1] xx = np.linspace(-5, 5) yy = a * xx - clf.intercept_[0] / w[1] wclf = svm.SVC(kernel='linear', class_weight={1: 10}) wclf.fit(X, y) ww = wclf.coef_[0] wa = -ww[0] / ww[1] wyy = wa * xx - wclf.intercept_[0] / ww[1] h0 = plt.plot(xx, yy, 'k-', label='no weights') h1 = plt.plot(xx, wyy, 'k--', label='with weights') plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired) plt.legend() plt.axis('tight') plt.show()
true
true
f727802bb39ec646082acbc4f4eca9a79e31fb09
1,827
py
Python
base.py
thiagosouzalink/Python_Projeto-CRUD_Using_File
20bc87568f1edd69aacc3af7b493b5b2337c6544
[ "MIT" ]
null
null
null
base.py
thiagosouzalink/Python_Projeto-CRUD_Using_File
20bc87568f1edd69aacc3af7b493b5b2337c6544
[ "MIT" ]
null
null
null
base.py
thiagosouzalink/Python_Projeto-CRUD_Using_File
20bc87568f1edd69aacc3af7b493b5b2337c6544
[ "MIT" ]
null
null
null
""" FUNÇÕES BÁSICAS PARA O PROGRAMA """ from time import sleep # Imprimir caracter especial def linha(tam=40): print(f"{'='*tam}") # Recebe e valida um nome def ler_nome(txt): stop = True while stop: stop = False nome = input(txt).strip() lista_nome = nome.split() if len(lista_nome) == 0: print("ERRO! Você digitou um nome vazio...") sleep(1) stop = True else: for valor in lista_nome: # Verifica se o nome contém conteúdo não alfabético if not valor.isalpha(): print("ERRO! Você digitou um nome inválido...") sleep(1) stop = True nome = " ".join(lista_nome) return nome # Recebe e valida um número inteiro def ler_inteiro(txt=""): # Caso o texto seja vazio, exibe uma mensagem default if txt == "": txt = "Digite o valor de um número inteiro" while True: try: inteiro = int(input(txt)) except (KeyboardInterrupt): print("ERRO! Entrada de dados interrompida pelo usuário!") inteiro = 0 break except(ValueError): print("ERRO! Você digitou um valor inteiro inválido...") sleep(1) except: # Demais erros print("ERRO! O programa teve um erro durante a leitura...") sleep(1) else: break return inteiro # Recebe e valida uma idade def ler_idade(txt): if txt == "": txt = "Digite o valor da idade" while True: idade = ler_inteiro(txt) if idade < 0: print("ERRO! Você digitou uma valor negativo...") sleep(1) else: break return idade
21.75
71
0.523262
from time import sleep def linha(tam=40): print(f"{'='*tam}") def ler_nome(txt): stop = True while stop: stop = False nome = input(txt).strip() lista_nome = nome.split() if len(lista_nome) == 0: print("ERRO! Você digitou um nome vazio...") sleep(1) stop = True else: for valor in lista_nome: if not valor.isalpha(): print("ERRO! Você digitou um nome inválido...") sleep(1) stop = True nome = " ".join(lista_nome) return nome def ler_inteiro(txt=""): if txt == "": txt = "Digite o valor de um número inteiro" while True: try: inteiro = int(input(txt)) except (KeyboardInterrupt): print("ERRO! Entrada de dados interrompida pelo usuário!") inteiro = 0 break except(ValueError): print("ERRO! Você digitou um valor inteiro inválido...") sleep(1) except: print("ERRO! O programa teve um erro durante a leitura...") sleep(1) else: break return inteiro def ler_idade(txt): if txt == "": txt = "Digite o valor da idade" while True: idade = ler_inteiro(txt) if idade < 0: print("ERRO! Você digitou uma valor negativo...") sleep(1) else: break return idade
true
true
f727809dfe02a4b21995583a93752cc365af2e33
162
py
Python
plugins/baiaozhi_cms.py
cflq3/getcms
6cf07da0ea3ec644866df715cff1f311a46ee378
[ "MIT" ]
22
2016-09-01T08:27:07.000Z
2021-01-11T13:32:59.000Z
plugins/baiaozhi_cms.py
cflq3/getcms
6cf07da0ea3ec644866df715cff1f311a46ee378
[ "MIT" ]
null
null
null
plugins/baiaozhi_cms.py
cflq3/getcms
6cf07da0ea3ec644866df715cff1f311a46ee378
[ "MIT" ]
20
2015-11-07T19:09:48.000Z
2018-05-02T03:10:41.000Z
#!/usr/bin/env python # encoding: utf-8 def run(whatweb, pluginname): whatweb.recog_from_file(pluginname, "portal/dbportal/popup/popupdiv.js", "'mozilla'")
23.142857
89
0.728395
def run(whatweb, pluginname): whatweb.recog_from_file(pluginname, "portal/dbportal/popup/popupdiv.js", "'mozilla'")
true
true
f72780a93d732aedce510f6fc8674fcf936b13b5
2,221
py
Python
test_compare_gw.py
namedyangfan/compare_gw
93d8ed205962c92c32d2cf669ee32eef18577d0e
[ "MIT" ]
null
null
null
test_compare_gw.py
namedyangfan/compare_gw
93d8ed205962c92c32d2cf669ee32eef18577d0e
[ "MIT" ]
null
null
null
test_compare_gw.py
namedyangfan/compare_gw
93d8ed205962c92c32d2cf669ee32eef18577d0e
[ "MIT" ]
null
null
null
from compare_data.compare_gw import Obs_well_hgs import unittest import os file_directory = os.path.join(os.getcwd(), 'test_data') output_folder = os.path.join(file_directory, "output") if not os.path.exists(output_folder): os.mkdir(output_folder) class TestStringMethods(unittest.TestCase): def test_reorder_hgsoutput(self): file_name = 'ARB_QUAPo.observation_well_flow.Baildon059.dat' test = Obs_well_hgs( file_directory = file_directory, file_name=file_name) test.read_raw_obs() test.reorder_raw2column(var_names = ['H', 'Z', 'S'], start_sheet = 3, end_sheet = 6, ldebug=False) test.op(op_folder = output_folder, zone_name = 'Baildon059_reorder') def test_reorder_hgsoutput_heat2depth(self): file_name = 'ARB_QUAPo.observation_well_flow.Baildon059.dat' test = Obs_well_hgs( file_directory = file_directory, file_name=file_name) test.read_raw_obs() test.reorder_raw2column(var_names = ['H', 'Z', 'S'], start_sheet = 3, end_sheet = 6, ldebug=False) test.head_to_depth() test.op(op_folder = output_folder, zone_name = 'Baildon059_head_2_depth') def test_simutime2realtime(self): file_name = 'ARB_QUAPo.observation_well_flow.Baildon059.dat' test = Obs_well_hgs( file_directory = file_directory, file_name= file_name) test.read_raw_obs() test.reorder_raw2column(var_names = ['H', 'Z', 'S'], start_sheet = 3, end_sheet = 6, ldebug=False) test.to_realtime(t0 = '2002-01-01T00:00:00Z') test.op(op_folder = output_folder, zone_name = 'Baildon059_realtime') def test_weekly_soilmoisture(self): file_name = 'ARB_QUAPo.observation_well_flow.Baildon059.dat' test = Obs_well_hgs( file_directory = file_directory, file_name= file_name) test.read_raw_obs() test.reorder_raw2column(var_names = ['H', 'Z', 'S'], start_sheet = 5, end_sheet = 6, ldebug=False) test.to_realtime(t0 = '2002-01-01T00:00:00Z') test.avg_weekly(date_format= 'YYYYMMDD') test.op(op_folder = output_folder, zone_name = 'Baildon059_weekly_soil_moisture') if __name__ == '__main__': unittest.main()
49.355556
107
0.693381
from compare_data.compare_gw import Obs_well_hgs import unittest import os file_directory = os.path.join(os.getcwd(), 'test_data') output_folder = os.path.join(file_directory, "output") if not os.path.exists(output_folder): os.mkdir(output_folder) class TestStringMethods(unittest.TestCase): def test_reorder_hgsoutput(self): file_name = 'ARB_QUAPo.observation_well_flow.Baildon059.dat' test = Obs_well_hgs( file_directory = file_directory, file_name=file_name) test.read_raw_obs() test.reorder_raw2column(var_names = ['H', 'Z', 'S'], start_sheet = 3, end_sheet = 6, ldebug=False) test.op(op_folder = output_folder, zone_name = 'Baildon059_reorder') def test_reorder_hgsoutput_heat2depth(self): file_name = 'ARB_QUAPo.observation_well_flow.Baildon059.dat' test = Obs_well_hgs( file_directory = file_directory, file_name=file_name) test.read_raw_obs() test.reorder_raw2column(var_names = ['H', 'Z', 'S'], start_sheet = 3, end_sheet = 6, ldebug=False) test.head_to_depth() test.op(op_folder = output_folder, zone_name = 'Baildon059_head_2_depth') def test_simutime2realtime(self): file_name = 'ARB_QUAPo.observation_well_flow.Baildon059.dat' test = Obs_well_hgs( file_directory = file_directory, file_name= file_name) test.read_raw_obs() test.reorder_raw2column(var_names = ['H', 'Z', 'S'], start_sheet = 3, end_sheet = 6, ldebug=False) test.to_realtime(t0 = '2002-01-01T00:00:00Z') test.op(op_folder = output_folder, zone_name = 'Baildon059_realtime') def test_weekly_soilmoisture(self): file_name = 'ARB_QUAPo.observation_well_flow.Baildon059.dat' test = Obs_well_hgs( file_directory = file_directory, file_name= file_name) test.read_raw_obs() test.reorder_raw2column(var_names = ['H', 'Z', 'S'], start_sheet = 5, end_sheet = 6, ldebug=False) test.to_realtime(t0 = '2002-01-01T00:00:00Z') test.avg_weekly(date_format= 'YYYYMMDD') test.op(op_folder = output_folder, zone_name = 'Baildon059_weekly_soil_moisture') if __name__ == '__main__': unittest.main()
true
true
f72783a0dd98fa8f7f24db93479956beeb8365a7
9,714
py
Python
operators/s3_to_mysql_operator.py
edbizarro/mysql_plugin
ce0175cec20319b996590e4d3e0ca36cf4331c10
[ "Apache-2.0" ]
15
2017-11-29T15:51:12.000Z
2022-02-09T13:19:33.000Z
operators/s3_to_mysql_operator.py
edbizarro/mysql_plugin
ce0175cec20319b996590e4d3e0ca36cf4331c10
[ "Apache-2.0" ]
5
2018-03-22T04:12:25.000Z
2019-04-30T21:14:00.000Z
operators/s3_to_mysql_operator.py
edbizarro/mysql_plugin
ce0175cec20319b996590e4d3e0ca36cf4331c10
[ "Apache-2.0" ]
20
2018-04-11T07:14:03.000Z
2021-09-14T01:17:20.000Z
from airflow.models import BaseOperator from airflow.hooks.S3_hook import S3Hook from airflow.hooks.mysql_hook import MySqlHook import dateutil.parser import json import logging class S3ToMySQLOperator(BaseOperator): """ NOTE: To avoid invalid characters, it is recommended to specify the character encoding (e.g {"charset":"utf8"}). S3 To MySQL Operator :param s3_conn_id: The source s3 connection id. :type s3_conn_id: string :param s3_bucket: The source s3 bucket. :type s3_bucket: string :param s3_key: The source s3 key. :type s3_key: string :param mysql_conn_id: The destination redshift connection id. :type mysql_conn_id: string :param database: The destination database name. :type database: string :param table: The destination mysql table name. :type table: string :param field_schema: An array of dicts in the following format: {'name': 'column_name', 'type': 'int(11)'} which determine what fields will be created and inserted. :type field_schema: array :param primary_key: The primary key for the destination table. Multiple strings in the array signify a compound key. :type primary_key: array :param incremental_key: *(optional)* The incremental key to compare new data against the destination table with. Only required if using a load_type of "upsert". :type incremental_key: string :param load_type: The method of loading into MySQL that should occur. Options are "append", "rebuild", and "upsert". Defaults to "append." :type load_type: string """ template_fields = ('s3_key',) def __init__(self, s3_conn_id, s3_bucket, s3_key, mysql_conn_id, database, table, field_schema, primary_key=[], incremental_key=None, load_type='append', *args, **kwargs): super().__init__(*args, **kwargs) self.mysql_conn_id = mysql_conn_id self.s3_conn_id = s3_conn_id self.s3_bucket = s3_bucket self.s3_key = s3_key self.table = table self.database = database self.field_schema = field_schema self.primary_key = primary_key self.incremental_key = incremental_key self.load_type = load_type def execute(self, context): m_hook = MySqlHook(self.mysql_conn_id) data = (S3Hook(self.s3_conn_id) .get_key(self.s3_key, bucket_name=self.s3_bucket) .get_contents_as_string(encoding='utf-8')) self.copy_data(m_hook, data) def copy_data(self, m_hook, data): if self.load_type == 'rebuild': drop_query = \ """ DROP TABLE IF EXISTS {schema}.{table} """.format(schema=self.database, table=self.table) m_hook.run(drop_query) table_exists_query = \ """ SELECT * FROM information_schema.tables WHERE table_schema = '{database}' AND table_name = '{table}' """.format(database=self.database, table=self.table) if not m_hook.get_records(table_exists_query): self.create_table(m_hook) else: self.reconcile_schemas(m_hook) self.write_data(m_hook, data) def create_table(self, m_hook): # Fields are surround by `` in order to avoid namespace conflicts # with reserved words in MySQL. # https://dev.mysql.com/doc/refman/5.7/en/identifiers.html fields = ['`{name}` {type} {nullable}'.format(name=field['name'], type=field['type'], nullable='NOT NULL' if field['name'] in self.primary_key else 'NULL') for field in self.field_schema] keys = ', '.join(self.primary_key) create_query = \ """ CREATE TABLE IF NOT EXISTS {schema}.{table} ({fields} """.format(schema=self.database, table=self.table, fields=', '.join(fields)) if keys: create_query += ', PRIMARY KEY (`{keys}`)'.format(keys=keys) create_query += ')' m_hook.run(create_query) def reconcile_schemas(self, m_hook): describe_query = 'DESCRIBE {schema}.{table}'.format(schema=self.database, table=self.table) records = m_hook.get_records(describe_query) existing_columns_names = [x[0] for x in records] incoming_column_names = [field['name'] for field in self.field_schema] missing_columns = list(set(incoming_column_names) - set(existing_columns_names)) if len(missing_columns): columns = ['ADD COLUMN {name} {type} NULL'.format(name=field['name'], type=field['type']) for field in self.field_schema if field['name'] in missing_columns] alter_query = \ """ ALTER TABLE {schema}.{table} {columns} """.format(schema=self.database, table=self.table, columns=', '.join(columns)) m_hook.run(alter_query) logging.info('The new columns were:' + str(missing_columns)) else: logging.info('There were no new columns.') def write_data(self, m_hook, data): fields = ', '.join([field['name'] for field in self.field_schema]) placeholders = ', '.join('%({name})s'.format(name=field['name']) for field in self.field_schema) insert_query = \ """ INSERT INTO {schema}.{table} ({columns}) VALUES ({placeholders}) """.format(schema=self.database, table=self.table, columns=fields, placeholders=placeholders) if self.load_type == 'upsert': # Add IF check to ensure that the records being inserted have an # incremental_key with a value greater than the existing records. update_set = ', '.join([""" {name} = IF({ik} < VALUES({ik}), VALUES({name}), {name}) """.format(name=field['name'], ik=self.incremental_key) for field in self.field_schema]) insert_query += ('ON DUPLICATE KEY UPDATE {update_set}' .format(update_set=update_set)) # Split the incoming JSON newlines string along new lines. # Remove cases where two or more '\n' results in empty entries. records = [record for record in data.split('\n') if record] # Create a default "record" object with all available fields # intialized to None. These will be overwritten with the proper # field values as available. default_object = {} for field in self.field_schema: default_object[field['name']] = None # Initialize null to Nonetype for incoming null values in records dict null = None output = [] for record in records: line_object = default_object.copy() line_object.update(json.loads(record)) output.append(line_object) date_fields = [field['name'] for field in self.field_schema if field['type'] in ['datetime', 'date']] def convert_timestamps(key, value): if key in date_fields: try: # Parse strings to look for values that match a timestamp # and convert to datetime. # Set ignoretz=False to keep timezones embedded in datetime. # http://bit.ly/2zwcebe value = dateutil.parser.parse(value, ignoretz=False) return value except (ValueError, TypeError, OverflowError): # If the value does not match a timestamp or is null, # return intial value. return value else: return value output = [dict([k, convert_timestamps(k, v)] if v is not None else [k, v] for k, v in i.items()) for i in output] conn = m_hook.get_conn() cur = conn.cursor() cur.executemany(insert_query, output) cur.close() conn.commit() conn.close()
40.475
109
0.50628
from airflow.models import BaseOperator from airflow.hooks.S3_hook import S3Hook from airflow.hooks.mysql_hook import MySqlHook import dateutil.parser import json import logging class S3ToMySQLOperator(BaseOperator): template_fields = ('s3_key',) def __init__(self, s3_conn_id, s3_bucket, s3_key, mysql_conn_id, database, table, field_schema, primary_key=[], incremental_key=None, load_type='append', *args, **kwargs): super().__init__(*args, **kwargs) self.mysql_conn_id = mysql_conn_id self.s3_conn_id = s3_conn_id self.s3_bucket = s3_bucket self.s3_key = s3_key self.table = table self.database = database self.field_schema = field_schema self.primary_key = primary_key self.incremental_key = incremental_key self.load_type = load_type def execute(self, context): m_hook = MySqlHook(self.mysql_conn_id) data = (S3Hook(self.s3_conn_id) .get_key(self.s3_key, bucket_name=self.s3_bucket) .get_contents_as_string(encoding='utf-8')) self.copy_data(m_hook, data) def copy_data(self, m_hook, data): if self.load_type == 'rebuild': drop_query = \ """ DROP TABLE IF EXISTS {schema}.{table} """.format(schema=self.database, table=self.table) m_hook.run(drop_query) table_exists_query = \ """ SELECT * FROM information_schema.tables WHERE table_schema = '{database}' AND table_name = '{table}' """.format(database=self.database, table=self.table) if not m_hook.get_records(table_exists_query): self.create_table(m_hook) else: self.reconcile_schemas(m_hook) self.write_data(m_hook, data) def create_table(self, m_hook): fields = ['`{name}` {type} {nullable}'.format(name=field['name'], type=field['type'], nullable='NOT NULL' if field['name'] in self.primary_key else 'NULL') for field in self.field_schema] keys = ', '.join(self.primary_key) create_query = \ """ CREATE TABLE IF NOT EXISTS {schema}.{table} ({fields} """.format(schema=self.database, table=self.table, fields=', '.join(fields)) if keys: create_query += ', PRIMARY KEY (`{keys}`)'.format(keys=keys) create_query += ')' m_hook.run(create_query) def reconcile_schemas(self, m_hook): describe_query = 'DESCRIBE {schema}.{table}'.format(schema=self.database, table=self.table) records = m_hook.get_records(describe_query) existing_columns_names = [x[0] for x in records] incoming_column_names = [field['name'] for field in self.field_schema] missing_columns = list(set(incoming_column_names) - set(existing_columns_names)) if len(missing_columns): columns = ['ADD COLUMN {name} {type} NULL'.format(name=field['name'], type=field['type']) for field in self.field_schema if field['name'] in missing_columns] alter_query = \ """ ALTER TABLE {schema}.{table} {columns} """.format(schema=self.database, table=self.table, columns=', '.join(columns)) m_hook.run(alter_query) logging.info('The new columns were:' + str(missing_columns)) else: logging.info('There were no new columns.') def write_data(self, m_hook, data): fields = ', '.join([field['name'] for field in self.field_schema]) placeholders = ', '.join('%({name})s'.format(name=field['name']) for field in self.field_schema) insert_query = \ """ INSERT INTO {schema}.{table} ({columns}) VALUES ({placeholders}) """.format(schema=self.database, table=self.table, columns=fields, placeholders=placeholders) if self.load_type == 'upsert': update_set = ', '.join([""" {name} = IF({ik} < VALUES({ik}), VALUES({name}), {name}) """.format(name=field['name'], ik=self.incremental_key) for field in self.field_schema]) insert_query += ('ON DUPLICATE KEY UPDATE {update_set}' .format(update_set=update_set)) records = [record for record in data.split('\n') if record] default_object = {} for field in self.field_schema: default_object[field['name']] = None null = None output = [] for record in records: line_object = default_object.copy() line_object.update(json.loads(record)) output.append(line_object) date_fields = [field['name'] for field in self.field_schema if field['type'] in ['datetime', 'date']] def convert_timestamps(key, value): if key in date_fields: try: value = dateutil.parser.parse(value, ignoretz=False) return value except (ValueError, TypeError, OverflowError): return value else: return value output = [dict([k, convert_timestamps(k, v)] if v is not None else [k, v] for k, v in i.items()) for i in output] conn = m_hook.get_conn() cur = conn.cursor() cur.executemany(insert_query, output) cur.close() conn.commit() conn.close()
true
true
f72783f41e43e7a6ced69380671e393ee8c3f52c
4,382
py
Python
contrib/seeds/generate-seeds.py
glemercier/Core-Smart
4ccc12a1b2a55cbad79ddee07449a5fdadf3082b
[ "MIT" ]
67
2018-05-17T21:54:01.000Z
2022-02-04T09:45:03.000Z
contrib/seeds/generate-seeds.py
glemercier/Core-Smart
4ccc12a1b2a55cbad79ddee07449a5fdadf3082b
[ "MIT" ]
11
2018-06-23T11:27:51.000Z
2021-02-20T17:54:18.000Z
contrib/seeds/generate-seeds.py
glemercier/Core-Smart
4ccc12a1b2a55cbad79ddee07449a5fdadf3082b
[ "MIT" ]
43
2018-05-09T07:27:58.000Z
2021-12-14T15:21:51.000Z
#!/usr/bin/python # Copyright (c) 2014 Wladimir J. van der Laan # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Script to generate list of seed nodes for chainparams.cpp. This script expects two text files in the directory that is passed as an argument: nodes_main.txt nodes_test.txt These files must consist of lines in the format <ip> <ip>:<port> [<ipv6>] [<ipv6>]:<port> <onion>.onion 0xDDBBCCAA (IPv4 little-endian old pnSeeds format) The output will be two data structures with the peers in binary format: static SeedSpec6 pnSeed6_main[]={ ... } static SeedSpec6 pnSeed6_test[]={ ... } These should be pasted into `src/chainparamsseeds.h`. ''' from __future__ import print_function, division from base64 import b32decode from binascii import a2b_hex import sys, os import re # ipv4 in ipv6 prefix pchIPv4 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff]) # tor-specific ipv6 prefix pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43]) def name_to_ipv6(addr): if len(addr)>6 and addr.endswith('.onion'): vchAddr = b32decode(addr[0:-6], True) if len(vchAddr) != 16-len(pchOnionCat): raise ValueError('Invalid onion %s' % s) return pchOnionCat + vchAddr elif '.' in addr: # IPv4 return pchIPv4 + bytearray((int(x) for x in addr.split('.'))) elif ':' in addr: # IPv6 sub = [[], []] # prefix, suffix x = 0 addr = addr.split(':') for i,comp in enumerate(addr): if comp == '': if i == 0 or i == (len(addr)-1): # skip empty component at beginning or end continue x += 1 # :: skips to suffix assert(x < 2) else: # two bytes per component val = int(comp, 16) sub[x].append(val >> 8) sub[x].append(val & 0xff) nullbytes = 16 - len(sub[0]) - len(sub[1]) assert((x == 0 and nullbytes == 0) or (x == 1 and nullbytes > 0)) return bytearray(sub[0] + ([0] * nullbytes) + sub[1]) elif addr.startswith('0x'): # IPv4-in-little-endian return pchIPv4 + bytearray(reversed(a2b_hex(addr[2:]))) else: raise ValueError('Could not parse address %s' % addr) def parse_spec(s, defaultport): match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s) if match: # ipv6 host = match.group(1) port = match.group(2) elif s.count(':') > 1: # ipv6, no port host = s port = '' else: (host,_,port) = s.partition(':') if not port: port = defaultport else: port = int(port) host = name_to_ipv6(host) return (host,port) def process_nodes(g, f, structname, defaultport): g.write('static SeedSpec6 %s[] = {\n' % structname) first = True for line in f: comment = line.find('#') if comment != -1: line = line[0:comment] line = line.strip() if not line: continue if not first: g.write(',\n') first = False (host,port) = parse_spec(line, defaultport) hoststr = ','.join(('0x%02x' % b) for b in host) g.write(' {{%s}, %i}' % (hoststr, port)) g.write('\n};\n') def main(): if len(sys.argv)<2: print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr) sys.exit(1) g = sys.stdout indir = sys.argv[1] g.write('#ifndef BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('#define BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('/**\n') g.write(' * List of fixed seed nodes for the bitcoin network\n') g.write(' * AUTOGENERATED by contrib/seeds/generate-seeds.py\n') g.write(' *\n') g.write(' * Each line contains a 16-byte IPv6 address and a port.\n') g.write(' * IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly.\n') g.write(' */\n') with open(os.path.join(indir,'nodes_main.txt'),'r') as f: process_nodes(g, f, 'pnSeed6_main', 9678) g.write('\n') with open(os.path.join(indir,'nodes_test.txt'),'r') as f: process_nodes(g, f, 'pnSeed6_test', 19678) g.write('#endif // BITCOIN_CHAINPARAMSSEEDS_H\n') if __name__ == '__main__': main()
31.52518
98
0.582611
from __future__ import print_function, division from base64 import b32decode from binascii import a2b_hex import sys, os import re pchIPv4 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff]) pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43]) def name_to_ipv6(addr): if len(addr)>6 and addr.endswith('.onion'): vchAddr = b32decode(addr[0:-6], True) if len(vchAddr) != 16-len(pchOnionCat): raise ValueError('Invalid onion %s' % s) return pchOnionCat + vchAddr elif '.' in addr: return pchIPv4 + bytearray((int(x) for x in addr.split('.'))) elif ':' in addr: sub = [[], []] x = 0 addr = addr.split(':') for i,comp in enumerate(addr): if comp == '': if i == 0 or i == (len(addr)-1): continue x += 1 assert(x < 2) else: val = int(comp, 16) sub[x].append(val >> 8) sub[x].append(val & 0xff) nullbytes = 16 - len(sub[0]) - len(sub[1]) assert((x == 0 and nullbytes == 0) or (x == 1 and nullbytes > 0)) return bytearray(sub[0] + ([0] * nullbytes) + sub[1]) elif addr.startswith('0x'): return pchIPv4 + bytearray(reversed(a2b_hex(addr[2:]))) else: raise ValueError('Could not parse address %s' % addr) def parse_spec(s, defaultport): match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s) if match: host = match.group(1) port = match.group(2) elif s.count(':') > 1: host = s port = '' else: (host,_,port) = s.partition(':') if not port: port = defaultport else: port = int(port) host = name_to_ipv6(host) return (host,port) def process_nodes(g, f, structname, defaultport): g.write('static SeedSpec6 %s[] = {\n' % structname) first = True for line in f: comment = line.find('#') if comment != -1: line = line[0:comment] line = line.strip() if not line: continue if not first: g.write(',\n') first = False (host,port) = parse_spec(line, defaultport) hoststr = ','.join(('0x%02x' % b) for b in host) g.write(' {{%s}, %i}' % (hoststr, port)) g.write('\n};\n') def main(): if len(sys.argv)<2: print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr) sys.exit(1) g = sys.stdout indir = sys.argv[1] g.write('#ifndef BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('#define BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('/**\n') g.write(' * List of fixed seed nodes for the bitcoin network\n') g.write(' * AUTOGENERATED by contrib/seeds/generate-seeds.py\n') g.write(' *\n') g.write(' * Each line contains a 16-byte IPv6 address and a port.\n') g.write(' * IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly.\n') g.write(' */\n') with open(os.path.join(indir,'nodes_main.txt'),'r') as f: process_nodes(g, f, 'pnSeed6_main', 9678) g.write('\n') with open(os.path.join(indir,'nodes_test.txt'),'r') as f: process_nodes(g, f, 'pnSeed6_test', 19678) g.write('#endif // BITCOIN_CHAINPARAMSSEEDS_H\n') if __name__ == '__main__': main()
true
true
f72785479e692aec1709c88b02e8f2700f756609
1,030
py
Python
userbot/plugins/alive.py
KING-USER1/BLACK-GHOULS-USERBOT-
3db2b42e2f27ce2b4d1fce3e8f016b269e872d05
[ "MIT" ]
null
null
null
userbot/plugins/alive.py
KING-USER1/BLACK-GHOULS-USERBOT-
3db2b42e2f27ce2b4d1fce3e8f016b269e872d05
[ "MIT" ]
null
null
null
userbot/plugins/alive.py
KING-USER1/BLACK-GHOULS-USERBOT-
3db2b42e2f27ce2b4d1fce3e8f016b269e872d05
[ "MIT" ]
null
null
null
"""Check if userbot alive. If you change these, you become the gayest gay such that even the gay world will disown you.""" import asyncio from telethon import events from telethon.tl.types import ChannelParticipantsAdmins from platform import uname from userbot import ALIVE_NAME from userbot.utils import admin_cmd DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else "Set ALIVE_NAME in config vars in Heroku" #@command(outgoing=True, pattern="^.alive$") @borg.on(admin_cmd(pattern=r"alive")) async def amireallyalive(alive): """ For .alive command, check if the bot is running. """ await alive.edit("`Abe Dalle Apna Kaam Kar Baap Ko Mat Dekh.\n\nBot version: 1.0\nPython: 3.7.3\n\n`" f"`Mera Maalik`: {DEFAULTUSER}\n" "`Telethon version: 6.9.0\nPython: 3.7.3\nfork by:` @KING_COBRA_OPPp\n" f"`Sabka Baap` : {DEFAULTUSER} \n" "`Always with my Maalik\n`" "[Deploy this userbot Now](https://github.com/KING-USER1/BLACK-GHOULS-USERBOT-)")
46.818182
122
0.683495
import asyncio from telethon import events from telethon.tl.types import ChannelParticipantsAdmins from platform import uname from userbot import ALIVE_NAME from userbot.utils import admin_cmd DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else "Set ALIVE_NAME in config vars in Heroku" @borg.on(admin_cmd(pattern=r"alive")) async def amireallyalive(alive): await alive.edit("`Abe Dalle Apna Kaam Kar Baap Ko Mat Dekh.\n\nBot version: 1.0\nPython: 3.7.3\n\n`" f"`Mera Maalik`: {DEFAULTUSER}\n" "`Telethon version: 6.9.0\nPython: 3.7.3\nfork by:` @KING_COBRA_OPPp\n" f"`Sabka Baap` : {DEFAULTUSER} \n" "`Always with my Maalik\n`" "[Deploy this userbot Now](https://github.com/KING-USER1/BLACK-GHOULS-USERBOT-)")
true
true
f727859e96eaa14fd00273ab0b71ffa22bdf4fcf
2,065
py
Python
web/src/contacto/views.py
DelegacionCienciasUSAL/delcien.usal.es
fbf445c05a13eaa9726b0d8823c3aa34c9334dd3
[ "Apache-2.0" ]
1
2018-12-06T19:34:12.000Z
2018-12-06T19:34:12.000Z
web/src/contacto/views.py
DelegacionCienciasUSAL/delcien.usal.es
fbf445c05a13eaa9726b0d8823c3aa34c9334dd3
[ "Apache-2.0" ]
6
2018-12-08T08:45:52.000Z
2018-12-08T08:56:19.000Z
web/src/contacto/views.py
DelegacionCienciasUSAL/delcien.usal.es
fbf445c05a13eaa9726b0d8823c3aa34c9334dd3
[ "Apache-2.0" ]
null
null
null
from django.core.mail import send_mail from django.conf import settings from django.shortcuts import render from django.http import Http404 from django.http import HttpResponseRedirect # Create your views here. def main( request): return( render( request, 'contacto/main.html', {'Titulo' : 'Contacto'})) def get_duda(request): referer = request.META.get('HTTP_REFERER') if request.method == 'GET': nombre = request.GET.get('nombre') correo = request.GET.get('correo') ambito = request.GET.get('ambito') duda = request.GET.get('duda') extra = request.GET.get('extra') prev_url = request.GET.get('prev_url') if(nombre != None and duda != None and prev_url != None): subject = f"WEBPAGE : Duda de {nombre} sobre {ambito}" message = f"{nombre} ( {correo} ):\n" message = message + f"Ambito : {ambito}\nDuda : \n{duda}\n\n{extra}" from_email = settings.EMAIL_HOST_USER to_list = [settings.EMAIL_HOST_USER,] send_mail(subject, message, from_email, to_list) return HttpResponseRedirect(referer) def get_colab(request): referer = request.META.get('HTTP_REFERER') if request.method == 'GET': nombre = request.GET.get('nombre') correo = request.GET.get('correo') ambito = request.GET.get('ambito') idea = request.GET.get('idea') extra = request.GET.get('extra') prev_url = request.GET.get('prev_url') if(nombre != None and idea != None and prev_url != None): subject = f"WEBPAGE : Propuesta de colaboración de {nombre} sobre {ambito}" message = f"{nombre} ( {correo} ):\n" message = message + f"Ambito : {ambito}\nidea : \n{idea}\n\n{extra}" from_email = settings.EMAIL_HOST_USER to_list = [settings.EMAIL_HOST_USER,] print(f'colab subject : {subject}\n{from_email}\ncorreo : \n{message}') send_mail(subject, message, from_email, to_list) return HttpResponseRedirect(referer)
43.020833
87
0.62954
from django.core.mail import send_mail from django.conf import settings from django.shortcuts import render from django.http import Http404 from django.http import HttpResponseRedirect def main( request): return( render( request, 'contacto/main.html', {'Titulo' : 'Contacto'})) def get_duda(request): referer = request.META.get('HTTP_REFERER') if request.method == 'GET': nombre = request.GET.get('nombre') correo = request.GET.get('correo') ambito = request.GET.get('ambito') duda = request.GET.get('duda') extra = request.GET.get('extra') prev_url = request.GET.get('prev_url') if(nombre != None and duda != None and prev_url != None): subject = f"WEBPAGE : Duda de {nombre} sobre {ambito}" message = f"{nombre} ( {correo} ):\n" message = message + f"Ambito : {ambito}\nDuda : \n{duda}\n\n{extra}" from_email = settings.EMAIL_HOST_USER to_list = [settings.EMAIL_HOST_USER,] send_mail(subject, message, from_email, to_list) return HttpResponseRedirect(referer) def get_colab(request): referer = request.META.get('HTTP_REFERER') if request.method == 'GET': nombre = request.GET.get('nombre') correo = request.GET.get('correo') ambito = request.GET.get('ambito') idea = request.GET.get('idea') extra = request.GET.get('extra') prev_url = request.GET.get('prev_url') if(nombre != None and idea != None and prev_url != None): subject = f"WEBPAGE : Propuesta de colaboración de {nombre} sobre {ambito}" message = f"{nombre} ( {correo} ):\n" message = message + f"Ambito : {ambito}\nidea : \n{idea}\n\n{extra}" from_email = settings.EMAIL_HOST_USER to_list = [settings.EMAIL_HOST_USER,] print(f'colab subject : {subject}\n{from_email}\ncorreo : \n{message}') send_mail(subject, message, from_email, to_list) return HttpResponseRedirect(referer)
true
true
f72785f26964192007bad38595a7da8e4e0b7024
629
py
Python
manage.py
BuildForSDG/frontend90
35b7297341f048b08a5ff02c7a96dad968004010
[ "MIT" ]
1
2020-11-16T11:54:29.000Z
2020-11-16T11:54:29.000Z
manage.py
BuildForSDG/frontend90
35b7297341f048b08a5ff02c7a96dad968004010
[ "MIT" ]
11
2020-05-17T18:39:21.000Z
2021-09-22T19:14:28.000Z
manage.py
BuildForSDG/frontend90
35b7297341f048b08a5ff02c7a96dad968004010
[ "MIT" ]
5
2020-05-18T11:19:44.000Z
2020-11-12T14:46:31.000Z
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'smartcity.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
28.590909
73
0.683625
import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'smartcity.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
true
true
f72786710d226ad55e4560292df4916f0c08622e
21,421
py
Python
gupb/controller/tup_tup.py
syforcee/GUPB
f916acf94efe61c54fa7b4cc33d3f94821fdb3d7
[ "MIT" ]
null
null
null
gupb/controller/tup_tup.py
syforcee/GUPB
f916acf94efe61c54fa7b4cc33d3f94821fdb3d7
[ "MIT" ]
null
null
null
gupb/controller/tup_tup.py
syforcee/GUPB
f916acf94efe61c54fa7b4cc33d3f94821fdb3d7
[ "MIT" ]
null
null
null
import random from itertools import product from queue import SimpleQueue from typing import Dict, Type, Optional, Tuple, List, Set from gupb.controller.tup_tup_resources.trained_model import QuartersRelation, MenhirToCentreDistance, Actions, MODEL from gupb.model import arenas, coordinates, weapons, tiles, characters, games FACING_ORDER = [characters.Facing.LEFT, characters.Facing.UP, characters.Facing.RIGHT, characters.Facing.DOWN] ARENA_NAMES = ['archipelago', 'dungeon', 'fisher_island', 'wasteland', 'island', 'mini'] IS_LEARNING = False ALPHA = 0.2 EPSILON = 0.2 GAMMA = 0.99 DEFAULT_VAL = 0 MENHIR_NEIGHBOURHOOD_DISTANCE = 5 CLOSE_DISTANCE_THRESHOLD = 13 MODERATE_DISTANCE_THRESHOLD = 19 # noinspection PyUnusedLocal # noinspection PyMethodMayBeStatic class TupTupController: def __init__(self, name_suffix): self.identifier: str = "TupTup" + name_suffix self.menhir_pos: coordinates.Coords = None self.facing: Optional[characters.Facing] = None self.position: coordinates.Coords = None self.weapon: Type[weapons.Weapon] = weapons.Knife self.action_queue: SimpleQueue[characters.Action] = SimpleQueue() self.has_calculated_path: bool = False self.path: List = [] self.bfs_goal: coordinates.Coords = None self.bfs_potential_goals: Set[coordinates.Coords] = set() self.bfs_potential_goals_visited: Set[coordinates.Coords] = set() self.map: Optional[arenas.Terrain] = None self.map_size: Optional[Tuple[int, int]] = None self.hiding_spot: coordinates.Coords = None self.mist_radius: int = 0 self.episode: int = 0 self.max_num_of_episodes: int = 0 self.arena_name: Optional[str] = None self.arena_data: Optional[Dict] = None self.arenas_knowledge: Dict = self.__init_model() self.game_no: int = 0 self.action: Optional[Actions] = None self.state: Optional[QuartersRelation, MenhirToCentreDistance] = None self.initial_position: coordinates.Coords = None def __eq__(self, other: object) -> bool: if isinstance(other, TupTupController) and other.name == self.name: return True return False def __hash__(self) -> int: return hash(self.identifier) def reset(self, arena_description: arenas.ArenaDescription) -> None: if self.arena_data and self.arena_data['attempt_no'] >= 1: self.arena_data['action'] = self.action self.arena_data['state'] = self.state self.arena_data['reward'] = self.__get_reward() self.arena_data['reward_sum'] += self.arena_data['reward'] self.action_queue = SimpleQueue() self.path = [] self.bfs_potential_goals = set() self.bfs_potential_goals_visited = set() self.has_calculated_path = False self.hiding_spot = None self.episode = 0 self.game_no += 1 arena = arenas.Arena.load(arena_description.name) self.arena_name = arena.name self.arena_data = self.arenas_knowledge[self.arena_name] self.arena_data['attempt_no'] += 1 self.map = arena.terrain self.map_size = arena.size self.mist_radius = int(self.map_size[0] * 2 ** 0.5) + 1 self.max_num_of_episodes = (self.mist_radius - 1) * games.MIST_TTH self.menhir_pos = arena_description.menhir_position self.bfs_goal = self.menhir_pos self.bfs_potential_goals_visited.add(self.menhir_pos) self.arena_data['epsilon'] *= 0.99 self.arena_data['alpha'] *= 0.99 def decide(self, knowledge: characters.ChampionKnowledge) -> characters.Action: self.episode += 1 try: self.__update_char_info(knowledge) if self.episode == 1: self.initial_position = self.position if self.arena_data['attempt_no'] == 1 and self.episode == 1: # if it is the first game on this map first_action = random.choice(list(Actions)) self.action = first_action self.state = self.__discretize() elif self.arena_data['attempt_no'] > 1 and self.episode == 1: # learn when a new game begins but after the first game reward = self.arena_data['reward'] action = self.arena_data['action'] state = self.arena_data['state'] new_action = self.__pick_action(state) new_state = self.__discretize() if IS_LEARNING: self.__learn(action, state, reward, new_action, new_state) self.action = new_action self.state = new_state if self.episode == 1 and self.__needs_to_hide(): self.__go_to_hiding_spot() if self.__is_enemy_in_range(knowledge.position, knowledge.visible_tiles): return characters.Action.ATTACK if not self.action_queue.empty(): return self.action_queue.get() if not self.has_calculated_path: start, end = self.position, self.bfs_goal self.__calculate_optimal_path(start, end) if len(self.path) > 0: # the path was found self.has_calculated_path = True else: neighbors = self.__get_neighbors(self.bfs_goal) for neighbor in neighbors: if neighbor not in self.bfs_potential_goals_visited: self.bfs_potential_goals.add(neighbor) if self.bfs_potential_goals: self.bfs_goal = self.bfs_potential_goals.pop() self.bfs_potential_goals_visited.add(self.bfs_goal) if not self.action_queue.empty(): return self.action_queue.get() if len(self.path) > 1 and self.__has_to_move(): self.__add_moves(2) else: # the destination is reached self.__guard_area() if not self.action_queue.empty(): return self.action_queue.get() return characters.Action.DO_NOTHING except Exception: return characters.Action.DO_NOTHING def __update_char_info(self, knowledge: characters.ChampionKnowledge) -> None: self.position = knowledge.position char_description = knowledge.visible_tiles[knowledge.position].character weapons_map = {w.__name__.lower(): w for w in [weapons.Knife, weapons.Sword, weapons.Bow, weapons.Amulet, weapons.Axe]} self.weapon = weapons_map.get(char_description.weapon.name, weapons.Knife) self.facing = char_description.facing def __needs_to_hide(self) -> bool: quarter = (self.position[0] // (self.map_size[0] / 2), self.position[1] // (self.map_size[1] / 2)) start_x, start_y = 0, 0 if self.action == Actions.HIDE_IN_THE_STARTING_QUARTER: start_x = self.map_size[0] - 1 if quarter[0] == 1.0 else 0 start_y = self.map_size[1] - 1 if quarter[1] == 1.0 else 0 elif self.action == Actions.HIDE_IN_THE_OPPOSITE_QUARTER: start_x = self.map_size[0] - 1 if quarter[0] == 0.0 else 0 start_y = self.map_size[1] - 1 if quarter[1] == 0.0 else 0 elif self.action == Actions.HIDE_IN_THE_NEIGHBOR_QUARTER_VERTICAL: start_x = self.map_size[0] - 1 if quarter[0] == 1.0 else 0 start_y = self.map_size[1] - 1 if quarter[1] == 0.0 else 0 elif self.action == Actions.HIDE_IN_THE_NEIGHBOR_QUARTER_HORIZONTAL: start_x = self.map_size[0] - 1 if quarter[0] == 0.0 else 0 start_y = self.map_size[1] - 1 if quarter[1] == 1.0 else 0 corner = {(start_x, start_y)} directions = [(1 if start_x == 0 else -1, 0), (0, 1 if start_y == 0 else -1)] hiding_spots = set() while not hiding_spots: for t in corner: if t in self.map and self.map[t].terrain_passable(): self.hiding_spot = coordinates.Coords(t[0], t[1]) hiding_spots.add(coordinates.Coords(t[0], t[1])) corner = {(t[0] + d[0], t[1] + d[1]) for t in corner for d in directions} for coords in hiding_spots: if self.map[coords].loot: self.hiding_spot = coords return True def __go_to_hiding_spot(self) -> None: start, end = self.position, self.hiding_spot self.__calculate_optimal_path(start, end) self.path.append(end) self.__add_moves(200) def __rotate(self, expected_facing: characters.Facing, starting_facing: characters.Facing = None) -> None: curr_facing_index = FACING_ORDER.index(self.facing if not starting_facing else starting_facing) expected_facing_index = FACING_ORDER.index(expected_facing) diff_expected_curr = expected_facing_index - curr_facing_index if diff_expected_curr < 0: diff_expected_curr += len(FACING_ORDER) if diff_expected_curr == 1: self.action_queue.put(characters.Action.TURN_RIGHT) elif diff_expected_curr == 2: self.action_queue.put(characters.Action.TURN_RIGHT) self.action_queue.put(characters.Action.TURN_RIGHT) elif diff_expected_curr == 3: self.action_queue.put(characters.Action.TURN_LEFT) def __has_to_move(self) -> bool: return self.episode >= self.max_num_of_episodes - len(self.path) * 5 def __guard_area(self) -> None: self.action_queue.put(characters.Action.TURN_RIGHT) def __is_enemy_in_range(self, position: coordinates.Coords, visible_tiles: Dict[coordinates.Coords, tiles.TileDescription]) -> bool: try: if issubclass(self.weapon, weapons.LineWeapon): weapon_reach = self.weapon.reach() tile_to_check = position for _ in range(1, self.weapon.reach() + 1): tile_to_check = tile_to_check + self.facing.value if visible_tiles[tile_to_check].character: return True elif isinstance(self.weapon, weapons.Amulet): for tile in [position + (1, 1), position + (-1, 1), position + (1, -1), position + (-1, -1)]: if tile in visible_tiles and visible_tiles[tile].character: return True elif isinstance(self.weapon, weapons.Axe): tiles_to_check = [coordinates.Coords(self.facing.value.x, i) for i in [-1, 0, 1]] \ if self.facing.value.x != 0 else [coordinates.Coords(i, self.facing.value.y) for i in [-1, 0, 1]] for tile in tiles_to_check: if tile in visible_tiles and visible_tiles[position + self.facing.value].character: return True else: return False except KeyError: # tile was not visible return False def __get_neighbors(self, coords): available_cells = [] for facing in characters.Facing: next_coords = coords + facing.value if next_coords in self.map and self.map[coords].terrain_passable(): available_cells.append(next_coords) return available_cells def __breadth_first_search(self, start_coords: coordinates.Coords, end_coords: coordinates.Coords) -> \ Dict[coordinates.Coords, Tuple[int, coordinates.Coords]]: queue = SimpleQueue() if self.map[start_coords].terrain_passable(): queue.put(start_coords) visited = set() path = {start_coords: start_coords} while not queue.empty(): cell = queue.get() if cell in visited: continue if cell == end_coords: return path visited.add(cell) for neighbour in self.__get_neighbors(cell): if neighbour not in path: path[neighbour] = cell queue.put(neighbour) raise BFSException("The shortest path wasn't found!") def __backtrack_path(self, end_coords: coordinates.Coords, start_coords: coordinates.Coords, path: Dict, final_path: List): if end_coords == start_coords: return self.facing, end_coords elif end_coords not in path.keys(): raise PathFindingException else: next_coord = path[end_coords] prev_facing, prev_coords = self.__backtrack_path(next_coord, start_coords, path, final_path) next_facing = characters.Facing(end_coords - next_coord) final_path.append(next_coord) return next_facing, next_coord def __get_rotations_number(self, current_facing: characters.Facing, next_facing: characters.Facing) -> int: curr_facing_index = FACING_ORDER.index(current_facing) next_facing_index = FACING_ORDER.index(next_facing) diff = next_facing_index - curr_facing_index if diff < 0: diff += len(FACING_ORDER) if diff % 2 != 0: return 1 elif diff == 2: return 2 return 0 def __calculate_optimal_path(self, start_coords: coordinates.Coords, end_coords: coordinates.Coords): try: bfs_res = self.__breadth_first_search(start_coords, end_coords) final_path = [] self.__backtrack_path(end_coords, start_coords, bfs_res, final_path) self.path = final_path except (BFSException, PathFindingException) as e: pass def __add_moves(self, number_of_moves=1) -> None: starting_facing = None for _ in range(number_of_moves): if len(self.path) < 2: break start_coords = self.path.pop(0) end_coords = self.path[0] starting_facing = self.__move(start_coords, end_coords, starting_facing) def __move(self, start_coords: coordinates.Coords, end_coords: coordinates.Coords, starting_facing: characters.Facing = None) -> characters.Facing: try: destination_facing = self.__get_destination_facing(end_coords, start_coords) self.__rotate(destination_facing, starting_facing) self.action_queue.put(characters.Action.STEP_FORWARD) return destination_facing except Exception: pass def __get_destination_facing(self, end_coords: coordinates.Coords, start_coords: coordinates.Coords) -> characters.Facing: coords_diff = end_coords - start_coords if coords_diff.y == 0: if coords_diff.x < 0: return characters.Facing.LEFT if coords_diff.x > 0: return characters.Facing.RIGHT elif coords_diff.x == 0: if coords_diff.y < 0: return characters.Facing.UP if coords_diff.y > 0: return characters.Facing.DOWN else: # one of the numbers SHOULD be 0, otherwise sth is wrong with the BFS result raise (Exception("The coordinates are not one step away from each other")) @property def name(self) -> str: return self.identifier @property def preferred_tabard(self) -> characters.Tabard: return characters.Tabard.YELLOW def __discretize(self) -> Tuple[QuartersRelation, MenhirToCentreDistance]: start_quarter = (self.position[0] // (self.map_size[0] / 2), self.position[1] // (self.map_size[1] / 2)) menhir_quarter = (self.menhir_pos[0] // (self.map_size[0] / 2), self.menhir_pos[1] // (self.map_size[1] / 2)) menhir_to_centre_distance = int(((self.map_size[0] // 2 - self.menhir_pos[0]) ** 2 + (self.map_size[1] // 2 - self.menhir_pos[1]) ** 2) ** 0.5) if start_quarter == menhir_quarter: if menhir_to_centre_distance < CLOSE_DISTANCE_THRESHOLD: return QuartersRelation.THE_SAME_QUARTER, MenhirToCentreDistance.CLOSE elif menhir_to_centre_distance < MODERATE_DISTANCE_THRESHOLD: return QuartersRelation.THE_SAME_QUARTER, MenhirToCentreDistance.MODERATE else: return QuartersRelation.THE_SAME_QUARTER, MenhirToCentreDistance.FAR elif (start_quarter[0] + menhir_quarter[0], start_quarter[1] + menhir_quarter[1]) == (1.0, 1.0): if menhir_to_centre_distance < CLOSE_DISTANCE_THRESHOLD: return QuartersRelation.OPPOSITE_QUARTERS, MenhirToCentreDistance.CLOSE elif menhir_to_centre_distance < MODERATE_DISTANCE_THRESHOLD: return QuartersRelation.OPPOSITE_QUARTERS, MenhirToCentreDistance.MODERATE else: return QuartersRelation.OPPOSITE_QUARTERS, MenhirToCentreDistance.FAR else: if menhir_to_centre_distance < CLOSE_DISTANCE_THRESHOLD: return QuartersRelation.NEIGHBOR_QUARTERS, MenhirToCentreDistance.CLOSE elif menhir_to_centre_distance < MODERATE_DISTANCE_THRESHOLD: return QuartersRelation.NEIGHBOR_QUARTERS, MenhirToCentreDistance.MODERATE else: return QuartersRelation.NEIGHBOR_QUARTERS, MenhirToCentreDistance.FAR def was_killed_by_mist(self) -> bool: mist_free_radius_when_died = self.mist_radius - self.episode // games.MIST_TTH radius_distance_to_menhir = int(((self.position[0] - self.menhir_pos[0]) ** 2 + (self.position[1] - self.menhir_pos[1]) ** 2) ** 0.5) return mist_free_radius_when_died <= radius_distance_to_menhir def __get_reward(self) -> int: killed_by_mist = self.was_killed_by_mist() if killed_by_mist: if not self.hiding_spot and self.initial_position == self.position: # camping in the initial position return 0 elif not self.has_calculated_path: # going to the hiding place return -3 elif len(self.path) > 0 and self.path[0] == self.hiding_spot: # camping in the hiding place return -2 elif len(self.path) > MENHIR_NEIGHBOURHOOD_DISTANCE and self.path[ 0] != self.hiding_spot: # going to the menhir position return -3 elif len(self.path) < MENHIR_NEIGHBOURHOOD_DISTANCE: return 3 else: if not self.hiding_spot and self.initial_position == self.position: return -2 elif not self.has_calculated_path: return -2 elif len(self.path) > 0 and self.path[0] == self.hiding_spot: return -2 elif len(self.path) > MENHIR_NEIGHBOURHOOD_DISTANCE and self.path[0] != self.hiding_spot: return -1 elif len(self.path) < MENHIR_NEIGHBOURHOOD_DISTANCE: return 2 return 0 def __pick_action(self, state: Tuple[QuartersRelation, MenhirToCentreDistance]) -> Actions: if random.uniform(0, 1) < self.arena_data['epsilon']: return random.choice(list(Actions)) else: knowledge = [self.arena_data['Q'].get((state, Actions.HIDE_IN_THE_STARTING_QUARTER), DEFAULT_VAL), self.arena_data['Q'].get((state, Actions.HIDE_IN_THE_OPPOSITE_QUARTER), DEFAULT_VAL), self.arena_data['Q'].get((state, Actions.HIDE_IN_THE_NEIGHBOR_QUARTER_HORIZONTAL), DEFAULT_VAL), self.arena_data['Q'].get((state, Actions.HIDE_IN_THE_NEIGHBOR_QUARTER_VERTICAL), DEFAULT_VAL)] max_value = max(knowledge) max_value_index = knowledge.index(max_value) return Actions(max_value_index) def __learn(self, action: Actions, state: Tuple[QuartersRelation, MenhirToCentreDistance], reward: int, new_action: Actions, new_state: Tuple[QuartersRelation, MenhirToCentreDistance]): old_value = self.arena_data['Q'].get((state, action), DEFAULT_VAL) future_value = self.arena_data['Q'].get((new_state, new_action), DEFAULT_VAL) if (state, action) not in self.arena_data['Q'].keys(): self.arena_data['Q'][(state, action)] = 0.0 self.arena_data['Q'][(state, action)] += self.arena_data['alpha'] * ( reward + self.arena_data['discount_factor'] * future_value - old_value) # if self.game_no % 50 == 0: # to show learning progress # print(self.arenas_knowledge) def __init_model(self) -> Dict: if IS_LEARNING: return {arena: { 'Q': {perm: 0.0 for perm in product(product(QuartersRelation, MenhirToCentreDistance), Actions)}, 'state': None, 'action': None, 'reward': None, 'reward_sum': 0, 'attempt_no': 0, 'alpha': ALPHA, 'epsilon': EPSILON, 'discount_factor': GAMMA} for arena in ARENA_NAMES} return MODEL class BFSException(Exception): pass class PathFindingException(Exception): pass POTENTIAL_CONTROLLERS = [ TupTupController('Bot'), ]
46.770742
130
0.6221
import random from itertools import product from queue import SimpleQueue from typing import Dict, Type, Optional, Tuple, List, Set from gupb.controller.tup_tup_resources.trained_model import QuartersRelation, MenhirToCentreDistance, Actions, MODEL from gupb.model import arenas, coordinates, weapons, tiles, characters, games FACING_ORDER = [characters.Facing.LEFT, characters.Facing.UP, characters.Facing.RIGHT, characters.Facing.DOWN] ARENA_NAMES = ['archipelago', 'dungeon', 'fisher_island', 'wasteland', 'island', 'mini'] IS_LEARNING = False ALPHA = 0.2 EPSILON = 0.2 GAMMA = 0.99 DEFAULT_VAL = 0 MENHIR_NEIGHBOURHOOD_DISTANCE = 5 CLOSE_DISTANCE_THRESHOLD = 13 MODERATE_DISTANCE_THRESHOLD = 19 class TupTupController: def __init__(self, name_suffix): self.identifier: str = "TupTup" + name_suffix self.menhir_pos: coordinates.Coords = None self.facing: Optional[characters.Facing] = None self.position: coordinates.Coords = None self.weapon: Type[weapons.Weapon] = weapons.Knife self.action_queue: SimpleQueue[characters.Action] = SimpleQueue() self.has_calculated_path: bool = False self.path: List = [] self.bfs_goal: coordinates.Coords = None self.bfs_potential_goals: Set[coordinates.Coords] = set() self.bfs_potential_goals_visited: Set[coordinates.Coords] = set() self.map: Optional[arenas.Terrain] = None self.map_size: Optional[Tuple[int, int]] = None self.hiding_spot: coordinates.Coords = None self.mist_radius: int = 0 self.episode: int = 0 self.max_num_of_episodes: int = 0 self.arena_name: Optional[str] = None self.arena_data: Optional[Dict] = None self.arenas_knowledge: Dict = self.__init_model() self.game_no: int = 0 self.action: Optional[Actions] = None self.state: Optional[QuartersRelation, MenhirToCentreDistance] = None self.initial_position: coordinates.Coords = None def __eq__(self, other: object) -> bool: if isinstance(other, TupTupController) and other.name == self.name: return True return False def __hash__(self) -> int: return hash(self.identifier) def reset(self, arena_description: arenas.ArenaDescription) -> None: if self.arena_data and self.arena_data['attempt_no'] >= 1: self.arena_data['action'] = self.action self.arena_data['state'] = self.state self.arena_data['reward'] = self.__get_reward() self.arena_data['reward_sum'] += self.arena_data['reward'] self.action_queue = SimpleQueue() self.path = [] self.bfs_potential_goals = set() self.bfs_potential_goals_visited = set() self.has_calculated_path = False self.hiding_spot = None self.episode = 0 self.game_no += 1 arena = arenas.Arena.load(arena_description.name) self.arena_name = arena.name self.arena_data = self.arenas_knowledge[self.arena_name] self.arena_data['attempt_no'] += 1 self.map = arena.terrain self.map_size = arena.size self.mist_radius = int(self.map_size[0] * 2 ** 0.5) + 1 self.max_num_of_episodes = (self.mist_radius - 1) * games.MIST_TTH self.menhir_pos = arena_description.menhir_position self.bfs_goal = self.menhir_pos self.bfs_potential_goals_visited.add(self.menhir_pos) self.arena_data['epsilon'] *= 0.99 self.arena_data['alpha'] *= 0.99 def decide(self, knowledge: characters.ChampionKnowledge) -> characters.Action: self.episode += 1 try: self.__update_char_info(knowledge) if self.episode == 1: self.initial_position = self.position if self.arena_data['attempt_no'] == 1 and self.episode == 1: first_action = random.choice(list(Actions)) self.action = first_action self.state = self.__discretize() elif self.arena_data['attempt_no'] > 1 and self.episode == 1: reward = self.arena_data['reward'] action = self.arena_data['action'] state = self.arena_data['state'] new_action = self.__pick_action(state) new_state = self.__discretize() if IS_LEARNING: self.__learn(action, state, reward, new_action, new_state) self.action = new_action self.state = new_state if self.episode == 1 and self.__needs_to_hide(): self.__go_to_hiding_spot() if self.__is_enemy_in_range(knowledge.position, knowledge.visible_tiles): return characters.Action.ATTACK if not self.action_queue.empty(): return self.action_queue.get() if not self.has_calculated_path: start, end = self.position, self.bfs_goal self.__calculate_optimal_path(start, end) if len(self.path) > 0: self.has_calculated_path = True else: neighbors = self.__get_neighbors(self.bfs_goal) for neighbor in neighbors: if neighbor not in self.bfs_potential_goals_visited: self.bfs_potential_goals.add(neighbor) if self.bfs_potential_goals: self.bfs_goal = self.bfs_potential_goals.pop() self.bfs_potential_goals_visited.add(self.bfs_goal) if not self.action_queue.empty(): return self.action_queue.get() if len(self.path) > 1 and self.__has_to_move(): self.__add_moves(2) else: self.__guard_area() if not self.action_queue.empty(): return self.action_queue.get() return characters.Action.DO_NOTHING except Exception: return characters.Action.DO_NOTHING def __update_char_info(self, knowledge: characters.ChampionKnowledge) -> None: self.position = knowledge.position char_description = knowledge.visible_tiles[knowledge.position].character weapons_map = {w.__name__.lower(): w for w in [weapons.Knife, weapons.Sword, weapons.Bow, weapons.Amulet, weapons.Axe]} self.weapon = weapons_map.get(char_description.weapon.name, weapons.Knife) self.facing = char_description.facing def __needs_to_hide(self) -> bool: quarter = (self.position[0] // (self.map_size[0] / 2), self.position[1] // (self.map_size[1] / 2)) start_x, start_y = 0, 0 if self.action == Actions.HIDE_IN_THE_STARTING_QUARTER: start_x = self.map_size[0] - 1 if quarter[0] == 1.0 else 0 start_y = self.map_size[1] - 1 if quarter[1] == 1.0 else 0 elif self.action == Actions.HIDE_IN_THE_OPPOSITE_QUARTER: start_x = self.map_size[0] - 1 if quarter[0] == 0.0 else 0 start_y = self.map_size[1] - 1 if quarter[1] == 0.0 else 0 elif self.action == Actions.HIDE_IN_THE_NEIGHBOR_QUARTER_VERTICAL: start_x = self.map_size[0] - 1 if quarter[0] == 1.0 else 0 start_y = self.map_size[1] - 1 if quarter[1] == 0.0 else 0 elif self.action == Actions.HIDE_IN_THE_NEIGHBOR_QUARTER_HORIZONTAL: start_x = self.map_size[0] - 1 if quarter[0] == 0.0 else 0 start_y = self.map_size[1] - 1 if quarter[1] == 1.0 else 0 corner = {(start_x, start_y)} directions = [(1 if start_x == 0 else -1, 0), (0, 1 if start_y == 0 else -1)] hiding_spots = set() while not hiding_spots: for t in corner: if t in self.map and self.map[t].terrain_passable(): self.hiding_spot = coordinates.Coords(t[0], t[1]) hiding_spots.add(coordinates.Coords(t[0], t[1])) corner = {(t[0] + d[0], t[1] + d[1]) for t in corner for d in directions} for coords in hiding_spots: if self.map[coords].loot: self.hiding_spot = coords return True def __go_to_hiding_spot(self) -> None: start, end = self.position, self.hiding_spot self.__calculate_optimal_path(start, end) self.path.append(end) self.__add_moves(200) def __rotate(self, expected_facing: characters.Facing, starting_facing: characters.Facing = None) -> None: curr_facing_index = FACING_ORDER.index(self.facing if not starting_facing else starting_facing) expected_facing_index = FACING_ORDER.index(expected_facing) diff_expected_curr = expected_facing_index - curr_facing_index if diff_expected_curr < 0: diff_expected_curr += len(FACING_ORDER) if diff_expected_curr == 1: self.action_queue.put(characters.Action.TURN_RIGHT) elif diff_expected_curr == 2: self.action_queue.put(characters.Action.TURN_RIGHT) self.action_queue.put(characters.Action.TURN_RIGHT) elif diff_expected_curr == 3: self.action_queue.put(characters.Action.TURN_LEFT) def __has_to_move(self) -> bool: return self.episode >= self.max_num_of_episodes - len(self.path) * 5 def __guard_area(self) -> None: self.action_queue.put(characters.Action.TURN_RIGHT) def __is_enemy_in_range(self, position: coordinates.Coords, visible_tiles: Dict[coordinates.Coords, tiles.TileDescription]) -> bool: try: if issubclass(self.weapon, weapons.LineWeapon): weapon_reach = self.weapon.reach() tile_to_check = position for _ in range(1, self.weapon.reach() + 1): tile_to_check = tile_to_check + self.facing.value if visible_tiles[tile_to_check].character: return True elif isinstance(self.weapon, weapons.Amulet): for tile in [position + (1, 1), position + (-1, 1), position + (1, -1), position + (-1, -1)]: if tile in visible_tiles and visible_tiles[tile].character: return True elif isinstance(self.weapon, weapons.Axe): tiles_to_check = [coordinates.Coords(self.facing.value.x, i) for i in [-1, 0, 1]] \ if self.facing.value.x != 0 else [coordinates.Coords(i, self.facing.value.y) for i in [-1, 0, 1]] for tile in tiles_to_check: if tile in visible_tiles and visible_tiles[position + self.facing.value].character: return True else: return False except KeyError: return False def __get_neighbors(self, coords): available_cells = [] for facing in characters.Facing: next_coords = coords + facing.value if next_coords in self.map and self.map[coords].terrain_passable(): available_cells.append(next_coords) return available_cells def __breadth_first_search(self, start_coords: coordinates.Coords, end_coords: coordinates.Coords) -> \ Dict[coordinates.Coords, Tuple[int, coordinates.Coords]]: queue = SimpleQueue() if self.map[start_coords].terrain_passable(): queue.put(start_coords) visited = set() path = {start_coords: start_coords} while not queue.empty(): cell = queue.get() if cell in visited: continue if cell == end_coords: return path visited.add(cell) for neighbour in self.__get_neighbors(cell): if neighbour not in path: path[neighbour] = cell queue.put(neighbour) raise BFSException("The shortest path wasn't found!") def __backtrack_path(self, end_coords: coordinates.Coords, start_coords: coordinates.Coords, path: Dict, final_path: List): if end_coords == start_coords: return self.facing, end_coords elif end_coords not in path.keys(): raise PathFindingException else: next_coord = path[end_coords] prev_facing, prev_coords = self.__backtrack_path(next_coord, start_coords, path, final_path) next_facing = characters.Facing(end_coords - next_coord) final_path.append(next_coord) return next_facing, next_coord def __get_rotations_number(self, current_facing: characters.Facing, next_facing: characters.Facing) -> int: curr_facing_index = FACING_ORDER.index(current_facing) next_facing_index = FACING_ORDER.index(next_facing) diff = next_facing_index - curr_facing_index if diff < 0: diff += len(FACING_ORDER) if diff % 2 != 0: return 1 elif diff == 2: return 2 return 0 def __calculate_optimal_path(self, start_coords: coordinates.Coords, end_coords: coordinates.Coords): try: bfs_res = self.__breadth_first_search(start_coords, end_coords) final_path = [] self.__backtrack_path(end_coords, start_coords, bfs_res, final_path) self.path = final_path except (BFSException, PathFindingException) as e: pass def __add_moves(self, number_of_moves=1) -> None: starting_facing = None for _ in range(number_of_moves): if len(self.path) < 2: break start_coords = self.path.pop(0) end_coords = self.path[0] starting_facing = self.__move(start_coords, end_coords, starting_facing) def __move(self, start_coords: coordinates.Coords, end_coords: coordinates.Coords, starting_facing: characters.Facing = None) -> characters.Facing: try: destination_facing = self.__get_destination_facing(end_coords, start_coords) self.__rotate(destination_facing, starting_facing) self.action_queue.put(characters.Action.STEP_FORWARD) return destination_facing except Exception: pass def __get_destination_facing(self, end_coords: coordinates.Coords, start_coords: coordinates.Coords) -> characters.Facing: coords_diff = end_coords - start_coords if coords_diff.y == 0: if coords_diff.x < 0: return characters.Facing.LEFT if coords_diff.x > 0: return characters.Facing.RIGHT elif coords_diff.x == 0: if coords_diff.y < 0: return characters.Facing.UP if coords_diff.y > 0: return characters.Facing.DOWN else: # one of the numbers SHOULD be 0, otherwise sth is wrong with the BFS result raise (Exception("The coordinates are not one step away from each other")) @property def name(self) -> str: return self.identifier @property def preferred_tabard(self) -> characters.Tabard: return characters.Tabard.YELLOW def __discretize(self) -> Tuple[QuartersRelation, MenhirToCentreDistance]: start_quarter = (self.position[0] // (self.map_size[0] / 2), self.position[1] // (self.map_size[1] / 2)) menhir_quarter = (self.menhir_pos[0] // (self.map_size[0] / 2), self.menhir_pos[1] // (self.map_size[1] / 2)) menhir_to_centre_distance = int(((self.map_size[0] // 2 - self.menhir_pos[0]) ** 2 + (self.map_size[1] // 2 - self.menhir_pos[1]) ** 2) ** 0.5) if start_quarter == menhir_quarter: if menhir_to_centre_distance < CLOSE_DISTANCE_THRESHOLD: return QuartersRelation.THE_SAME_QUARTER, MenhirToCentreDistance.CLOSE elif menhir_to_centre_distance < MODERATE_DISTANCE_THRESHOLD: return QuartersRelation.THE_SAME_QUARTER, MenhirToCentreDistance.MODERATE else: return QuartersRelation.THE_SAME_QUARTER, MenhirToCentreDistance.FAR elif (start_quarter[0] + menhir_quarter[0], start_quarter[1] + menhir_quarter[1]) == (1.0, 1.0): if menhir_to_centre_distance < CLOSE_DISTANCE_THRESHOLD: return QuartersRelation.OPPOSITE_QUARTERS, MenhirToCentreDistance.CLOSE elif menhir_to_centre_distance < MODERATE_DISTANCE_THRESHOLD: return QuartersRelation.OPPOSITE_QUARTERS, MenhirToCentreDistance.MODERATE else: return QuartersRelation.OPPOSITE_QUARTERS, MenhirToCentreDistance.FAR else: if menhir_to_centre_distance < CLOSE_DISTANCE_THRESHOLD: return QuartersRelation.NEIGHBOR_QUARTERS, MenhirToCentreDistance.CLOSE elif menhir_to_centre_distance < MODERATE_DISTANCE_THRESHOLD: return QuartersRelation.NEIGHBOR_QUARTERS, MenhirToCentreDistance.MODERATE else: return QuartersRelation.NEIGHBOR_QUARTERS, MenhirToCentreDistance.FAR def was_killed_by_mist(self) -> bool: mist_free_radius_when_died = self.mist_radius - self.episode // games.MIST_TTH radius_distance_to_menhir = int(((self.position[0] - self.menhir_pos[0]) ** 2 + (self.position[1] - self.menhir_pos[1]) ** 2) ** 0.5) return mist_free_radius_when_died <= radius_distance_to_menhir def __get_reward(self) -> int: killed_by_mist = self.was_killed_by_mist() if killed_by_mist: if not self.hiding_spot and self.initial_position == self.position: # camping in the initial position return 0 elif not self.has_calculated_path: # going to the hiding place return -3 elif len(self.path) > 0 and self.path[0] == self.hiding_spot: # camping in the hiding place return -2 elif len(self.path) > MENHIR_NEIGHBOURHOOD_DISTANCE and self.path[ 0] != self.hiding_spot: # going to the menhir position return -3 elif len(self.path) < MENHIR_NEIGHBOURHOOD_DISTANCE: return 3 else: if not self.hiding_spot and self.initial_position == self.position: return -2 elif not self.has_calculated_path: return -2 elif len(self.path) > 0 and self.path[0] == self.hiding_spot: return -2 elif len(self.path) > MENHIR_NEIGHBOURHOOD_DISTANCE and self.path[0] != self.hiding_spot: return -1 elif len(self.path) < MENHIR_NEIGHBOURHOOD_DISTANCE: return 2 return 0 def __pick_action(self, state: Tuple[QuartersRelation, MenhirToCentreDistance]) -> Actions: if random.uniform(0, 1) < self.arena_data['epsilon']: return random.choice(list(Actions)) else: knowledge = [self.arena_data['Q'].get((state, Actions.HIDE_IN_THE_STARTING_QUARTER), DEFAULT_VAL), self.arena_data['Q'].get((state, Actions.HIDE_IN_THE_OPPOSITE_QUARTER), DEFAULT_VAL), self.arena_data['Q'].get((state, Actions.HIDE_IN_THE_NEIGHBOR_QUARTER_HORIZONTAL), DEFAULT_VAL), self.arena_data['Q'].get((state, Actions.HIDE_IN_THE_NEIGHBOR_QUARTER_VERTICAL), DEFAULT_VAL)] max_value = max(knowledge) max_value_index = knowledge.index(max_value) return Actions(max_value_index) def __learn(self, action: Actions, state: Tuple[QuartersRelation, MenhirToCentreDistance], reward: int, new_action: Actions, new_state: Tuple[QuartersRelation, MenhirToCentreDistance]): old_value = self.arena_data['Q'].get((state, action), DEFAULT_VAL) future_value = self.arena_data['Q'].get((new_state, new_action), DEFAULT_VAL) if (state, action) not in self.arena_data['Q'].keys(): self.arena_data['Q'][(state, action)] = 0.0 self.arena_data['Q'][(state, action)] += self.arena_data['alpha'] * ( reward + self.arena_data['discount_factor'] * future_value - old_value) # if self.game_no % 50 == 0: # to show learning progress # print(self.arenas_knowledge) def __init_model(self) -> Dict: if IS_LEARNING: return {arena: { 'Q': {perm: 0.0 for perm in product(product(QuartersRelation, MenhirToCentreDistance), Actions)}, 'state': None, 'action': None, 'reward': None, 'reward_sum': 0, 'attempt_no': 0, 'alpha': ALPHA, 'epsilon': EPSILON, 'discount_factor': GAMMA} for arena in ARENA_NAMES} return MODEL class BFSException(Exception): pass class PathFindingException(Exception): pass POTENTIAL_CONTROLLERS = [ TupTupController('Bot'), ]
true
true
f72786a183d595e15dd09c998f2bd8b55855c064
314
py
Python
singletask_cli/context.py
lenaKuznetsova/singletask-cli
fb7910c090ddfc8ec9a721536808396abb20bfc3
[ "MIT" ]
null
null
null
singletask_cli/context.py
lenaKuznetsova/singletask-cli
fb7910c090ddfc8ec9a721536808396abb20bfc3
[ "MIT" ]
null
null
null
singletask_cli/context.py
lenaKuznetsova/singletask-cli
fb7910c090ddfc8ec9a721536808396abb20bfc3
[ "MIT" ]
null
null
null
from singletask_sql.settings import BASE_DIR, dotenv_values from singletask_sql.engine import create_engine # todo - config after auth env_path = [ f'{BASE_DIR}/../.env', f'{BASE_DIR}/../.env.local' ] conf = {} for path in env_path: conf.update(dotenv_values(path)) sql_engine = create_engine(conf)
20.933333
59
0.72293
from singletask_sql.settings import BASE_DIR, dotenv_values from singletask_sql.engine import create_engine env_path = [ f'{BASE_DIR}/../.env', f'{BASE_DIR}/../.env.local' ] conf = {} for path in env_path: conf.update(dotenv_values(path)) sql_engine = create_engine(conf)
true
true
f7278700e1134610692fcc8ae7f5634a20a9f268
560
py
Python
tasks/migrations/0009_alter_task_org.py
jordanm88/Django-CRM
5faf22acb30aeb32f5830898fd5d8ecd1ac0bbd8
[ "MIT" ]
1,334
2017-06-04T07:47:14.000Z
2022-03-30T17:12:37.000Z
tasks/migrations/0009_alter_task_org.py
AhmedDoudou/Django-CRM-1
5faf22acb30aeb32f5830898fd5d8ecd1ac0bbd8
[ "MIT" ]
317
2017-06-04T07:48:13.000Z
2022-03-29T19:24:26.000Z
tasks/migrations/0009_alter_task_org.py
AhmedDoudou/Django-CRM-1
5faf22acb30aeb32f5830898fd5d8ecd1ac0bbd8
[ "MIT" ]
786
2017-06-06T09:18:48.000Z
2022-03-29T01:29:29.000Z
# Generated by Django 3.2.7 on 2021-10-06 07:21 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('common', '0037_alter_profile_org'), ('tasks', '0008_rename_company_task_org'), ] operations = [ migrations.AlterField( model_name='task', name='org', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='task_org', to='common.org'), ), ]
26.666667
147
0.644643
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('common', '0037_alter_profile_org'), ('tasks', '0008_rename_company_task_org'), ] operations = [ migrations.AlterField( model_name='task', name='org', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='task_org', to='common.org'), ), ]
true
true
f72788069b5b787b60c74366778c57c504270b5a
14,226
py
Python
mmtbx/cablam/cablam_res.py
rimmartin/cctbx_project
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
[ "BSD-3-Clause-LBNL" ]
null
null
null
mmtbx/cablam/cablam_res.py
rimmartin/cctbx_project
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
[ "BSD-3-Clause-LBNL" ]
null
null
null
mmtbx/cablam/cablam_res.py
rimmartin/cctbx_project
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
[ "BSD-3-Clause-LBNL" ]
null
null
null
from __future__ import division # (jEdit options) :folding=explicit:collapseFolds=1: #This module contains the linked_residue class and the functions needed to build # and access instances of it. #2012-09-05: # prunerestype() moved to this module from cablam_training # linked_residue.id_with_resname() changed to return pdb-column-formatted ids #2012-10-09: # self.resid is now stored in each linked_residue object #2013_02_01: Added a step in linked_residue.__init__() that flags HETATOMs and a # step in construct_linked_residues() that skips adding them to the # resdata/protein object. Will this be a problem for synthetic or other # non-standard residues? #2013-09-17: changed formatting for id_with_resname to rg.atom.pdb_label_columns # Tried to add handling for HETATOMS in __init__. May or may not fully work. #Next: added mp_id() to produce MolPribity-friendly resids import sys from mmtbx.cablam.cablam_math import veclen, vectorize #{{{ linked_residue class #This class holds information on protein residues (as defined by residue_group # in pdb.hierarchy). See the __init__ for details. It also maintains sequence # relationships through a connectivity check and references "prevres" and # "nextres" to the class instances of sequence-adjacent residues. The intent is # to allow easy stepping forward and backward through the residue sequence. #For example: self.resnum returns the current residue number, # self.nextres.resnum returns the residue number of the next residue in # sequence, if such a residue exists. This is not protected by a .get or # anything, so you have to do your own error catching, usually of the form: # if self.nextres: return self.nextres.resnum #The class was designed for use with cablam, which requires forward and backward # sequence awareness, but it could be used elsewhere. It contains a generic # results={} dictionary usable by anyone willing to make unique keys for their # data. #It is recommended that all instances of this class for a protein be members of # some iterable (I use a dictionary keyed with the cablam_key() function in # this module). Do not rely on sequence connectivity alone (which breaks due to # multiple chains or missing atoms) to let you find all residues. #The class should deal with insertion codes well, since different icodes seem to # be in different rg's in the hierarchy. #The class does not deal with alts well, however, as an rg may contain several # ag's. The firstalt() function provides some relief, but is really a dodge # rather than a fix. I do not expect this to be a problem at low resolution # (where alts are rare), but it does present a problem for high-res training. #------------------------------------------------------------------------------- class linked_residue(object): #Prints kinemage point-style output for a list of measures given in kinorder def printtokin(self, kinorder, writeto=sys.stdout): outline = ['{'+self.pdbid+' '+self.id_with_resname()+'}'] for order in kinorder: try: outline.append(str(self.measures[order])) except KeyError: return writeto.write(' '.join(outline)+'\n') #Prints comma-separated output for a list of measures given in kinorder def printtocsv(self, kinorder, doconnections=False, writeto=sys.stdout): outline = [self.id_with_resname()] for order in kinorder: try: outline.append(str(self.measures[order])) except KeyError: outline.append('NULL') if doconnections: if self.prevres: outline.append(self.prevres.id_with_resname()) else: outline.append('NULL') if self.nextres: outline.append(self.nextres.id_with_resname()) else: outline.append('NULL') writeto.write(','.join(outline)+'\n') #note the ',' in the join here #id_to_string and id_with_resname return string concatenations of residue # identifiers. The identifier order should be standard with other RLab def id_to_str(self, sep=' '): resid_string = sep.join( [self.pdbid, self.model, self.chain, str(self.resnum), self.icode]) return resid_string def id_with_resname(self): # Formatted as: 'ALA A####I' resid_string = self.rg.atoms()[0].pdb_label_columns()[5:] return resid_string def mp_id(self): #An id consistent with MolProbity 'cnit' ids #Formatted as: ccnnnnilttt # c: 2-char Chain ID, space for none # n: sequence number, right justified, space padded # i: insertion code, space for none # l: alternate ID, space for none # t: residue type (ALA, LYS, etc.), all caps left justified, space padded #(Not sure about the 2-char Chain IDs just yet) #(alternates are not going to be handled properly yet) resid_string = self.id_with_resname() resname = resid_string[0:3] chain = resid_string[3:5] resnum = resid_string[5:9] ins = resid_string[9:10] alt = self.firstalt("CA") if alt is None or alt == '': alt = " " mpid_string = chain + resnum + ins + alt + resname return mpid_string #Removes the references that sequence-adjacent linked_residue class instances # have to this instance. Helps maintain correct sequence connectivity and may # allow this instance to be removed from memory. #Used in cablam_training.stripB() and cablam_training.prunerestype() def removelinks(self): if self.prevres: self.prevres.nextres = None if self.nextres: self.nextres.prevres = None #Returns the first alt index in alts that has an atom of the requested name # Removes some guesswork from atom lookup, but really just acrobatics around # the problem of how to store and access alts usefully def firstalt(self, atomname): for alt in self.alts: try: if self.atomxyz[alt][atomname]: return alt else: continue except KeyError: continue else: return None #simplified retrieval around firstalt for the common case of atom coords def getatomxyz(self, atomname): firstalt = self.firstalt(atomname) try: return self.atomxyz[firstalt][atomname] except KeyError: return None #There needs to be a CA-only consecutive check. Adding one is a high priority. def consecutive(self, res1, res2): if res1 and res2: #check against empties try: C = res1.atomxyz[res1.firstalt('C')]['C'] N = res2.atomxyz[res2.firstalt('N')]['N'] #firstalt returns None if it can't find an atom, # and a key of None gives a KeyError here except KeyError: #if there aren't a C and an N, assume the two are not properly bonded return False bondlen = veclen(vectorize(C,N)) if bondlen <= 2.0: #2.0A is the peptide bond cutoff used by O for model building and # potentially-fragmented chains. O's generous cutoff seemed appropriate # since I expect to process in-progress models with this program #RLab (probably) uses 1.4 +- 0.3, official textbook is about 1.33 #O's Ca-Ca distance is 4.5A return True else: return False else: return False def seq_dist(self, otherres): ############################################ # Returns distance in sequence with insertion codes accounted for. # The return value is negative if res is N-terminal to this. # The return value is positive if res is C-terminal to this. # The return value is None if res couldn't be found due to chain break etc. ############################################ if self is otherres: return 0 if self.chain != otherres.chain:# or self.model != otherres.model: return None #guess which direction to look # the "<=" and ">=" should let this look back or forward from within an # insertion if self.resnum <= otherres.resnum: delta = 0 cur = self while cur != None: delta += 1 if cur.nextres is otherres: return delta cur = cur.nextres if self.resnum >= otherres.resnum: delta = 0 cur = self while cur != None: delta -= 1 if cur.prevres is otherres: return delta cur = cur.prevres return None def __init__(self, rg, prevres=None, pdbid='pdbid', modelid='', chainid='', targetatoms=["CA","O","C","N"] ): self.rg = rg #the source residue group is preserved for additional data and #ease in transfering back to hierarchy mode self.pdbid = pdbid self.model = modelid self.chain = chainid self.resnum = int(rg.resseq.strip()) #self.resseq = rg.resid[:-1] self.icode = rg.icode self.resid = cablam_key(self.model, self.chain, self.resnum, self.icode) self.hetero = False #marks whether this is a HETATOM #alts: 'alt' and 'resname' keyed by ag.altloc in the form of '','A','B' etc. #atomxyz: xyz coords, indexed by ag.altloc, and atom.name within each alt # e.g. atomxyz['']['CA'] returns the coordinates of a non-alt Calpha #atomb: atomic b, indexed by ag.altloc, and atom.name within each alt self.alts = {} self.atomxyz = {} self.atomb = {} ### What about anisou? Not handled yet. #hierachy looping and data extraction for ag in rg.atom_groups(): #if not ag.is_protein(): Need sopmething like this that works # self.is_protein=True self.alts[ag.altloc] = {'alt':ag.altloc, 'resname':ag.resname} self.atomxyz[ag.altloc] = {} self.atomb[ag.altloc] = {} for atom in ag.atoms(): if atom.hetero and ag.resname.upper() != 'MSE': self.hetero=True for targetatom in targetatoms: if atom.name.strip() == targetatom: self.atomxyz[ag.altloc][targetatom] = atom.xyz self.atomb[ag.altloc][targetatom] = atom.b #Note that a reference to the related residue is stored, not a dictionary # key for the wrapper dictionary #Someone clever may want to teach me how to use weakref() if the mutual # references that result from this cause memory problems if prevres and self.consecutive(prevres, self): self.prevres = prevres #Connect this residue to previous prevres.nextres = self #And the previous residue to this one else: self.prevres = None #Adjacency is handled in an outside function self.nextres = None self.probe = {'O':{},'H':{}} #holder for hydrogen bonding, indexed by 'target' residue+atom, see cablam_training.add_probe_data() self.probeH = [] self.probeO = [] self.measures = {} #Holder for cablam-space geometric measures self.motifs = {} #Holder for identified motifs from fingerprints/probetrain self.results = {} #Generic holder for calcuated values of interest #------------------------------------------------------------------------------- #}}} #{{{ prunerestype function #Deletes all members of a given residue type from a dictionary of residues #"Residue type" is determined from pdb.hierarchy's ag.resname, the upshot being # that non-residues like "HOH" waters and het groups can also be pruned to # improve performance if their three-letter codes are known. #------------------------------------------------------------------------------- def prunerestype(resdata, restype): reslist = resdata.keys() for residue in reslist: for alt in resdata[residue].alts: if resdata[residue].alts[alt]['resname'].strip() == restype: resdata[residue].removelinks() trash = resdata.pop(residue) break #------------------------------------------------------------------------------- #}}} #{{{ cablam_key function #The "protein" or "resdata" dictionary returned by construct_linked_residues() # below uses a particular key construction to access (and order) its contents #This function provides that construction so that residues in resdata may be # accessed from anywhere. The string returned is .sort()able #------------------------------------------------------------------------------- def cablam_key(modelid=None, chainid=None, resnum=None, icode=None): if None not in [modelid, chainid, resnum, icode]: resid_string = ' '.join([modelid, chainid, '%04i' % resnum, icode]) #The bit of string formatting here ('%04i' % resnum) helps .sort() later by # adding 0's to the left side of resnum until resnum is 4 characters long. # May or may not be compatible with Hybrid36 or other numbering schemes. return resid_string else: sys.stderr.write(""" Missing value for cablam_res.cablam_key(pdbid, modelid, chainid, resnum, icode) Please pass complete information """) sys.exit() #------------------------------------------------------------------------------- #}}} #{{{ construct_linked_residues function #------------------------------------------------------------------------------- #This function returns a dictionary of linked_residue objects with keys as # defined by cablam_key() above. It is responsible for iterating over part of # the hierarchy, but most of the work is done by the __init__() in the # linked_residue class. #targetatoms handling is likely to see some change as I add compatibility for # CA-only mainchain traces. Currently "C" and "N" are necessary for the # sequency adjacency check linked_residue.consecutive(), which checks for # appropriate peptide bond length #targetatoms is a list of strings that identify pdb atoms, e.g. "CA" or "CD1" def construct_linked_residues( hierarchy, targetatoms=["CA","O","C","N"], pdbid='pdbid' ): protein = {} for model in hierarchy.models(): for chain in model.chains(): prevres = None for rg in chain.residue_groups(): residue = linked_residue( rg, prevres=prevres, pdbid=pdbid, modelid=model.id, chainid=chain.id, targetatoms=targetatoms) resid_string = cablam_key(model.id, chain.id, residue.resnum, rg.icode) if not residue.hetero: #automatically skip het atoms protein[resid_string] = residue prevres = residue #important update for determining connectivity return protein #------------------------------------------------------------------------------- #}}}
43.638037
135
0.659145
from __future__ import division import sys from mmtbx.cablam.cablam_math import veclen, vectorize #The class does not deal with alts well, however, as an rg may contain several # ag's. The firstalt() function provides some relief, but is really a dodge class linked_residue(object): def printtokin(self, kinorder, writeto=sys.stdout): outline = ['{'+self.pdbid+' '+self.id_with_resname()+'}'] for order in kinorder: try: outline.append(str(self.measures[order])) except KeyError: return writeto.write(' '.join(outline)+'\n') def printtocsv(self, kinorder, doconnections=False, writeto=sys.stdout): outline = [self.id_with_resname()] for order in kinorder: try: outline.append(str(self.measures[order])) except KeyError: outline.append('NULL') if doconnections: if self.prevres: outline.append(self.prevres.id_with_resname()) else: outline.append('NULL') if self.nextres: outline.append(self.nextres.id_with_resname()) else: outline.append('NULL') writeto.write(','.join(outline)+'\n') def id_to_str(self, sep=' '): resid_string = sep.join( [self.pdbid, self.model, self.chain, str(self.resnum), self.icode]) return resid_string def id_with_resname(self): resid_string = self.rg.atoms()[0].pdb_label_columns()[5:] return resid_string def mp_id(self): resid_string = self.id_with_resname() resname = resid_string[0:3] chain = resid_string[3:5] resnum = resid_string[5:9] ins = resid_string[9:10] alt = self.firstalt("CA") if alt is None or alt == '': alt = " " mpid_string = chain + resnum + ins + alt + resname return mpid_string def removelinks(self): if self.prevres: self.prevres.nextres = None if self.nextres: self.nextres.prevres = None def firstalt(self, atomname): for alt in self.alts: try: if self.atomxyz[alt][atomname]: return alt else: continue except KeyError: continue else: return None def getatomxyz(self, atomname): firstalt = self.firstalt(atomname) try: return self.atomxyz[firstalt][atomname] except KeyError: return None def consecutive(self, res1, res2): if res1 and res2: try: C = res1.atomxyz[res1.firstalt('C')]['C'] N = res2.atomxyz[res2.firstalt('N')]['N'] # and a key of None gives a KeyError here except KeyError: #if there aren't a C and an N, assume the two are not properly bonded return False bondlen = veclen(vectorize(C,N)) if bondlen <= 2.0: # since I expect to process in-progress models with this program #RLab (probably) uses 1.4 +- 0.3, official textbook is about 1.33 #O's Ca-Ca distance is 4.5A return True else: return False else: return False def seq_dist(self, otherres): ransfering back to hierarchy mode self.pdbid = pdbid self.model = modelid self.chain = chainid self.resnum = int(rg.resseq.strip()) #self.resseq = rg.resid[:-1] self.icode = rg.icode self.resid = cablam_key(self.model, self.chain, self.resnum, self.icode) self.hetero = False #marks whether this is a HETATOM #alts: 'alt' and 'resname' keyed by ag.altloc in the form of '','A','B' etc. #atomxyz: xyz coords, indexed by ag.altloc, and atom.name within each alt # e.g. atomxyz['']['CA'] returns the coordinates of a non-alt Calpha #atomb: atomic b, indexed by ag.altloc, and atom.name within each alt self.alts = {} self.atomxyz = {} self.atomb = {} ### What about anisou? Not handled yet. #hierachy looping and data extraction for ag in rg.atom_groups(): #if not ag.is_protein(): Need sopmething like this that works # self.is_protein=True self.alts[ag.altloc] = {'alt':ag.altloc, 'resname':ag.resname} self.atomxyz[ag.altloc] = {} self.atomb[ag.altloc] = {} for atom in ag.atoms(): if atom.hetero and ag.resname.upper() != 'MSE': self.hetero=True for targetatom in targetatoms: if atom.name.strip() == targetatom: self.atomxyz[ag.altloc][targetatom] = atom.xyz self.atomb[ag.altloc][targetatom] = atom.b #Note that a reference to the related residue is stored, not a dictionary # key for the wrapper dictionary #Someone clever may want to teach me how to use weakref() if the mutual # references that result from this cause memory problems if prevres and self.consecutive(prevres, self): self.prevres = prevres #Connect this residue to previous prevres.nextres = self #And the previous residue to this one else: self.prevres = None #Adjacency is handled in an outside function self.nextres = None self.probe = {'O':{},'H':{}} #holder for hydrogen bonding, indexed by 'target' residue+atom, see cablam_training.add_probe_data() self.probeH = [] self.probeO = [] self.measures = {} #Holder for cablam-space geometric measures self.motifs = {} #Holder for identified motifs from fingerprints/probetrain self.results = {} #Generic holder for calcuated values of interest #------------------------------------------------------------------------------- #}}} #{{{ prunerestype function #Deletes all members of a given residue type from a dictionary of residues #"Residue type" is determined from pdb.hierarchy's ag.resname, the upshot being def prunerestype(resdata, restype): reslist = resdata.keys() for residue in reslist: for alt in resdata[residue].alts: if resdata[residue].alts[alt]['resname'].strip() == restype: resdata[residue].removelinks() trash = resdata.pop(residue) break def cablam_key(modelid=None, chainid=None, resnum=None, icode=None): if None not in [modelid, chainid, resnum, icode]: resid_string = ' '.join([modelid, chainid, '%04i' % resnum, icode]) # May or may not be compatible with Hybrid36 or other numbering schemes. return resid_string else: sys.stderr.write(""" Missing value for cablam_res.cablam_key(pdbid, modelid, chainid, resnum, icode) Please pass complete information """) sys.exit() #------------------------------------------------------------------------------- #}}} #{{{ construct_linked_residues function #------------------------------------------------------------------------------- #This function returns a dictionary of linked_residue objects with keys as # defined by cablam_key() above. It is responsible for iterating over part of # the hierarchy, but most of the work is done by the __init__() in the # linked_residue class. #targetatoms handling is likely to see some change as I add compatibility for # CA-only mainchain traces. Currently "C" and "N" are necessary for the # sequency adjacency check linked_residue.consecutive(), which checks for # appropriate peptide bond length #targetatoms is a list of strings that identify pdb atoms, e.g. "CA" or "CD1" def construct_linked_residues( hierarchy, targetatoms=["CA","O","C","N"], pdbid='pdbid' ): protein = {} for model in hierarchy.models(): for chain in model.chains(): prevres = None for rg in chain.residue_groups(): residue = linked_residue( rg, prevres=prevres, pdbid=pdbid, modelid=model.id, chainid=chain.id, targetatoms=targetatoms) resid_string = cablam_key(model.id, chain.id, residue.resnum, rg.icode) if not residue.hetero: #automatically skip het atoms protein[resid_string] = residue prevres = residue #important update for determining connectivity return protein #------------------------------------------------------------------------------- #}}}
true
true
f7278954301c90c618734d8aadfe80011bdfffd8
1,640
py
Python
Community/ServiceNow CMDB/cmdb_switches/cmdb_switches_logic.py
spenney-bc/gateway-workflows
0311a9224b2d53c01689eb6a9a0a593177abed63
[ "Apache-2.0" ]
43
2017-12-04T17:38:24.000Z
2021-12-29T09:17:17.000Z
Community/ServiceNow CMDB/cmdb_switches/cmdb_switches_logic.py
spenney-bc/gateway-workflows
0311a9224b2d53c01689eb6a9a0a593177abed63
[ "Apache-2.0" ]
49
2017-12-07T21:02:29.000Z
2022-02-04T22:27:16.000Z
Community/ServiceNow CMDB/cmdb_switches/cmdb_switches_logic.py
spenney-bc/gateway-workflows
0311a9224b2d53c01689eb6a9a0a593177abed63
[ "Apache-2.0" ]
82
2017-12-04T17:56:00.000Z
2021-12-29T09:17:21.000Z
""" Component logic """ from bluecat.util import get_password_from_file from ..cmdb_configuration import cmdb_config import requests def raw_table_data(*args, **kwargs): # pylint: disable=redefined-outer-name data = {'columns': [{'title': 'Name'}, {'title': 'IP Address'}, {'title': 'Serial Number'}, {'title': 'Manufacturer'}, ], 'data': []} # HTTP request headers = {"Accept": "application/json"} cmdb_url = cmdb_config.servicenow_url + '/api/now/table/cmdb_ci_ip_switch' response = requests.get(cmdb_url, auth=(cmdb_config.servicenow_username, get_password_from_file(cmdb_config.servicenow_secret_file)), headers=headers, verify=False) # Check for HTTP codes other than 200 if response.status_code == 200: switches = response.json() for switch in switches['result']: switch_name = switch['name'] switch_ip = switch['ip_address'] switch_serial = switch['serial_number'] if switch['manufacturer']: switch_manufacturer = get_switch_manufacturer(switch['manufacturer']['link']) data['data'].append([switch_name, switch_ip, switch_serial, switch_manufacturer]) return data def get_switch_manufacturer(link): headers = {"Accept": "application/json"} response = requests.get(link, auth=(cmdb_config.servicenow_username, get_password_from_file(cmdb_config.servicenow_secret_file)), headers=headers, verify=False) manufacturer = response.json() return manufacturer['result']['name']
35.652174
168
0.64878
from bluecat.util import get_password_from_file from ..cmdb_configuration import cmdb_config import requests def raw_table_data(*args, **kwargs): data = {'columns': [{'title': 'Name'}, {'title': 'IP Address'}, {'title': 'Serial Number'}, {'title': 'Manufacturer'}, ], 'data': []} headers = {"Accept": "application/json"} cmdb_url = cmdb_config.servicenow_url + '/api/now/table/cmdb_ci_ip_switch' response = requests.get(cmdb_url, auth=(cmdb_config.servicenow_username, get_password_from_file(cmdb_config.servicenow_secret_file)), headers=headers, verify=False) if response.status_code == 200: switches = response.json() for switch in switches['result']: switch_name = switch['name'] switch_ip = switch['ip_address'] switch_serial = switch['serial_number'] if switch['manufacturer']: switch_manufacturer = get_switch_manufacturer(switch['manufacturer']['link']) data['data'].append([switch_name, switch_ip, switch_serial, switch_manufacturer]) return data def get_switch_manufacturer(link): headers = {"Accept": "application/json"} response = requests.get(link, auth=(cmdb_config.servicenow_username, get_password_from_file(cmdb_config.servicenow_secret_file)), headers=headers, verify=False) manufacturer = response.json() return manufacturer['result']['name']
true
true
f727899ef981f97f2b9272fee3b9581691701dbe
7,848
py
Python
src/pymor/bindings/ngsolve.py
meretp/pymor
0965a5c3d0725466103efae5190493fceb2bf441
[ "Unlicense" ]
null
null
null
src/pymor/bindings/ngsolve.py
meretp/pymor
0965a5c3d0725466103efae5190493fceb2bf441
[ "Unlicense" ]
null
null
null
src/pymor/bindings/ngsolve.py
meretp/pymor
0965a5c3d0725466103efae5190493fceb2bf441
[ "Unlicense" ]
null
null
null
# This file is part of the pyMOR project (https://www.pymor.org). # Copyright 2013-2021 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (https://opensource.org/licenses/BSD-2-Clause) from pathlib import Path from pymor.core.config import config from pymor.core.defaults import defaults from pymor.tools.io import change_to_directory if config.HAVE_NGSOLVE: import ngsolve as ngs import numpy as np from pymor.core.base import ImmutableObject from pymor.operators.list import LinearComplexifiedListVectorArrayOperatorBase from pymor.vectorarrays.interface import VectorArray from pymor.vectorarrays.numpy import NumpyVectorSpace from pymor.vectorarrays.list import CopyOnWriteVector, ComplexifiedVector, ComplexifiedListVectorSpace class NGSolveVectorCommon: def amax(self): A = np.abs(self.to_numpy()) max_ind = np.argmax(A) max_val = A[max_ind] return max_ind, max_val def dofs(self, dof_indices): return self.to_numpy()[dof_indices] class NGSolveVector(NGSolveVectorCommon, CopyOnWriteVector): """Wraps a NGSolve BaseVector to make it usable with ListVectorArray.""" def __init__(self, impl): self.impl = impl @classmethod def from_instance(cls, instance): return cls(instance.impl) def _copy_data(self): new_impl = ngs.GridFunction(self.impl.space) new_impl.vec.data = self.impl.vec self.impl = new_impl def to_numpy(self, ensure_copy=False): if ensure_copy: return self.impl.vec.FV().NumPy().copy() self._copy_data_if_needed() return self.impl.vec.FV().NumPy() def _scal(self, alpha): self.impl.vec.data = float(alpha) * self.impl.vec def _axpy(self, alpha, x): self.impl.vec.data = self.impl.vec + float(alpha) * x.impl.vec def inner(self, other): return self.impl.vec.InnerProduct(other.impl.vec) def norm(self): return self.impl.vec.Norm() def norm2(self): return self.impl.vec.Norm() ** 2 class ComplexifiedNGSolveVector(NGSolveVectorCommon, ComplexifiedVector): pass class NGSolveVectorSpace(ComplexifiedListVectorSpace): complexified_vector_type = ComplexifiedNGSolveVector def __init__(self, V, id='STATE'): self.__auto_init(locals()) def __eq__(self, other): return type(other) is NGSolveVectorSpace and self.V == other.V and self.id == other.id def __hash__(self): return hash(self.V) + hash(self.id) @property def value_dim(self): u = self.V.TrialFunction() if isinstance(u, list): return u[0].dim else: return u.dim @property def dim(self): return self.V.ndofglobal * self.value_dim @classmethod def space_from_vector_obj(cls, vec, id): return cls(vec.space, id) def real_zero_vector(self): impl = ngs.GridFunction(self.V) return NGSolveVector(impl) def real_make_vector(self, obj): return NGSolveVector(obj) def real_vector_from_numpy(self, data, ensure_copy=False): v = self.real_zero_vector() v.to_numpy()[:] = data return v class NGSolveMatrixOperator(LinearComplexifiedListVectorArrayOperatorBase): """Wraps a NGSolve matrix as an |Operator|.""" def __init__(self, matrix, range, source, solver_options=None, name=None): self.__auto_init(locals()) @defaults('default_solver') def _prepare_apply(self, U, mu, kind, least_squares=False, default_solver=''): if kind == 'apply_inverse': if least_squares: raise NotImplementedError solver = self.solver_options.get('inverse', default_solver) if self.solver_options else default_solver inv = self.matrix.Inverse(self.source.V.FreeDofs(), inverse=solver) return inv def _real_apply_one_vector(self, u, mu=None, prepare_data=None): r = self.range.real_zero_vector() self.matrix.Mult(u.impl.vec, r.impl.vec) return r def _real_apply_adjoint_one_vector(self, v, mu=None, prepare_data=None): u = self.source.real_zero_vector() try: mat = self.matrix.Transpose() except AttributeError: mat = self.matrix.T mat.Mult(v.impl.vec, u.impl.vec) return u def _real_apply_inverse_one_vector(self, v, mu=None, initial_guess=None, least_squares=False, prepare_data=None): inv = prepare_data r = self.source.real_zero_vector() r.impl.vec.data = inv * v.impl.vec return r def _assemble_lincomb(self, operators, coefficients, identity_shift=0., solver_options=None, name=None): if not all(isinstance(op, NGSolveMatrixOperator) for op in operators): return None if identity_shift != 0: return None matrix = operators[0].matrix.CreateMatrix() matrix.AsVector().data = float(coefficients[0]) * matrix.AsVector() for op, c in zip(operators[1:], coefficients[1:]): matrix.AsVector().data += float(c) * op.matrix.AsVector() return NGSolveMatrixOperator(matrix, self.range, self.source, solver_options=solver_options, name=name) def as_vector(self, copy=True): vec = self.matrix.AsVector().FV().NumPy() return NumpyVectorSpace.make_array(vec.copy() if copy else vec) class NGSolveVisualizer(ImmutableObject): """Visualize an NGSolve grid function.""" def __init__(self, mesh, fespace): self.__auto_init(locals()) self.space = NGSolveVectorSpace(fespace) def visualize(self, U, legend=None, separate_colorbars=True, filename=None, block=True): """Visualize the provided data.""" if isinstance(U, VectorArray): U = (U,) assert all(u in self.space for u in U) if any(len(u) != 1 for u in U): raise NotImplementedError if any(u._list[0].imag_part is not None for u in U): raise NotImplementedError if legend is None: legend = [f'VectorArray{i}' for i in range(len(U))] if isinstance(legend, str): legend = [legend] assert len(legend) == len(U) legend = [l.replace(' ', '_') for l in legend] # NGSolve GUI will fail otherwise if filename: # ngsolve unconditionnaly appends ".vtk" filename = Path(filename).resolve() if filename.suffix == '.vtk': filename = filename.parent / filename.stem else: self.logger.warning(f'NGSolve set VTKOutput filename to {filename}.vtk') coeffs = [u._list[0].real_part.impl for u in U] # ngsolve cannot handle full paths for filenames with change_to_directory(filename.parent): vtk = ngs.VTKOutput(ma=self.mesh, coefs=coeffs, names=legend, filename=str(filename), subdivision=0) vtk.Do() else: if not separate_colorbars: raise NotImplementedError for u, name in zip(U, legend): ngs.Draw(u._list[0].real_part.impl, self.mesh, name=name)
38.660099
120
0.599261
from pathlib import Path from pymor.core.config import config from pymor.core.defaults import defaults from pymor.tools.io import change_to_directory if config.HAVE_NGSOLVE: import ngsolve as ngs import numpy as np from pymor.core.base import ImmutableObject from pymor.operators.list import LinearComplexifiedListVectorArrayOperatorBase from pymor.vectorarrays.interface import VectorArray from pymor.vectorarrays.numpy import NumpyVectorSpace from pymor.vectorarrays.list import CopyOnWriteVector, ComplexifiedVector, ComplexifiedListVectorSpace class NGSolveVectorCommon: def amax(self): A = np.abs(self.to_numpy()) max_ind = np.argmax(A) max_val = A[max_ind] return max_ind, max_val def dofs(self, dof_indices): return self.to_numpy()[dof_indices] class NGSolveVector(NGSolveVectorCommon, CopyOnWriteVector): def __init__(self, impl): self.impl = impl @classmethod def from_instance(cls, instance): return cls(instance.impl) def _copy_data(self): new_impl = ngs.GridFunction(self.impl.space) new_impl.vec.data = self.impl.vec self.impl = new_impl def to_numpy(self, ensure_copy=False): if ensure_copy: return self.impl.vec.FV().NumPy().copy() self._copy_data_if_needed() return self.impl.vec.FV().NumPy() def _scal(self, alpha): self.impl.vec.data = float(alpha) * self.impl.vec def _axpy(self, alpha, x): self.impl.vec.data = self.impl.vec + float(alpha) * x.impl.vec def inner(self, other): return self.impl.vec.InnerProduct(other.impl.vec) def norm(self): return self.impl.vec.Norm() def norm2(self): return self.impl.vec.Norm() ** 2 class ComplexifiedNGSolveVector(NGSolveVectorCommon, ComplexifiedVector): pass class NGSolveVectorSpace(ComplexifiedListVectorSpace): complexified_vector_type = ComplexifiedNGSolveVector def __init__(self, V, id='STATE'): self.__auto_init(locals()) def __eq__(self, other): return type(other) is NGSolveVectorSpace and self.V == other.V and self.id == other.id def __hash__(self): return hash(self.V) + hash(self.id) @property def value_dim(self): u = self.V.TrialFunction() if isinstance(u, list): return u[0].dim else: return u.dim @property def dim(self): return self.V.ndofglobal * self.value_dim @classmethod def space_from_vector_obj(cls, vec, id): return cls(vec.space, id) def real_zero_vector(self): impl = ngs.GridFunction(self.V) return NGSolveVector(impl) def real_make_vector(self, obj): return NGSolveVector(obj) def real_vector_from_numpy(self, data, ensure_copy=False): v = self.real_zero_vector() v.to_numpy()[:] = data return v class NGSolveMatrixOperator(LinearComplexifiedListVectorArrayOperatorBase): def __init__(self, matrix, range, source, solver_options=None, name=None): self.__auto_init(locals()) @defaults('default_solver') def _prepare_apply(self, U, mu, kind, least_squares=False, default_solver=''): if kind == 'apply_inverse': if least_squares: raise NotImplementedError solver = self.solver_options.get('inverse', default_solver) if self.solver_options else default_solver inv = self.matrix.Inverse(self.source.V.FreeDofs(), inverse=solver) return inv def _real_apply_one_vector(self, u, mu=None, prepare_data=None): r = self.range.real_zero_vector() self.matrix.Mult(u.impl.vec, r.impl.vec) return r def _real_apply_adjoint_one_vector(self, v, mu=None, prepare_data=None): u = self.source.real_zero_vector() try: mat = self.matrix.Transpose() except AttributeError: mat = self.matrix.T mat.Mult(v.impl.vec, u.impl.vec) return u def _real_apply_inverse_one_vector(self, v, mu=None, initial_guess=None, least_squares=False, prepare_data=None): inv = prepare_data r = self.source.real_zero_vector() r.impl.vec.data = inv * v.impl.vec return r def _assemble_lincomb(self, operators, coefficients, identity_shift=0., solver_options=None, name=None): if not all(isinstance(op, NGSolveMatrixOperator) for op in operators): return None if identity_shift != 0: return None matrix = operators[0].matrix.CreateMatrix() matrix.AsVector().data = float(coefficients[0]) * matrix.AsVector() for op, c in zip(operators[1:], coefficients[1:]): matrix.AsVector().data += float(c) * op.matrix.AsVector() return NGSolveMatrixOperator(matrix, self.range, self.source, solver_options=solver_options, name=name) def as_vector(self, copy=True): vec = self.matrix.AsVector().FV().NumPy() return NumpyVectorSpace.make_array(vec.copy() if copy else vec) class NGSolveVisualizer(ImmutableObject): def __init__(self, mesh, fespace): self.__auto_init(locals()) self.space = NGSolveVectorSpace(fespace) def visualize(self, U, legend=None, separate_colorbars=True, filename=None, block=True): if isinstance(U, VectorArray): U = (U,) assert all(u in self.space for u in U) if any(len(u) != 1 for u in U): raise NotImplementedError if any(u._list[0].imag_part is not None for u in U): raise NotImplementedError if legend is None: legend = [f'VectorArray{i}' for i in range(len(U))] if isinstance(legend, str): legend = [legend] assert len(legend) == len(U) legend = [l.replace(' ', '_') for l in legend] if filename: filename = Path(filename).resolve() if filename.suffix == '.vtk': filename = filename.parent / filename.stem else: self.logger.warning(f'NGSolve set VTKOutput filename to {filename}.vtk') coeffs = [u._list[0].real_part.impl for u in U] with change_to_directory(filename.parent): vtk = ngs.VTKOutput(ma=self.mesh, coefs=coeffs, names=legend, filename=str(filename), subdivision=0) vtk.Do() else: if not separate_colorbars: raise NotImplementedError for u, name in zip(U, legend): ngs.Draw(u._list[0].real_part.impl, self.mesh, name=name)
true
true
f72789d0e4c9455e928dc2d9cfcad8d7f2a69dd2
6,167
py
Python
video_pipeline.py
josehoras/Advanced-Lane-Finding
e6b83d602eb89661d3bf0f4d257ed5af0f6a58bb
[ "MIT" ]
null
null
null
video_pipeline.py
josehoras/Advanced-Lane-Finding
e6b83d602eb89661d3bf0f4d257ed5af0f6a58bb
[ "MIT" ]
null
null
null
video_pipeline.py
josehoras/Advanced-Lane-Finding
e6b83d602eb89661d3bf0f4d257ed5af0f6a58bb
[ "MIT" ]
null
null
null
import numpy as np import pickle import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from moviepy.editor import VideoFileClip from image_thresholding import * from plotting_helpers import * from line_fit import * from Line import * # *** PIPELINE *** def pipeline(img): global error_im, skipped_frames # 1. Correct distorsion # open distorsion matrix try: saved_dist = pickle.load(open('calibrate_camera.p', 'rb'), encoding='latin1') mtx = saved_dist['mtx'] dist = saved_dist['dist'] except (OSError, IOError): # No progress file yet available print("No saved distorsion data. Run camera_calibration.py") # apply correction undist = cv2.undistort(img, mtx, dist, None, mtx) # 2. Apply filters to get binary map ksize = 3 gradx = abs_sobel_thresh(undist, orient='x', sobel_kernel=ksize, thresh=(10, 100)) grady = abs_sobel_thresh(undist, orient='y', sobel_kernel=ksize, thresh=(5, 100)) mag_bin = mag_thresh(undist, sobel_kernel=ksize, mag_thresh=(10, 200)) dir_bin = dir_threshold(undist, sobel_kernel=15, thresh=(0.9, 1.2)) hls_bin = hls_select(img, thresh=(50, 255)) white_bin = white_select(img, thresh=195) yellow_bin = yellow_select(img) # combine filters to a final output combined = np.zeros_like(dir_bin) combined[((mag_bin == 1) & (dir_bin == 1) & (hls_bin == 1)) | ((white_bin == 1) | (yellow_bin == 1))] = 1 # 3. Define trapezoid points on the road and transform perspective X = combined.shape[1] Y = combined.shape[0] src = np.float32( [[205, 720], [1075, 720], [700, 460], [580, 460]]) dst = np.float32( [[300, 720], [980, 720], [980, 0], [300, 0]]) # get perspective transformation matrix M = cv2.getPerspectiveTransform(src, dst) Minv = cv2.getPerspectiveTransform(dst, src) # warp the result of binary thresholds warped = cv2.warpPerspective(combined, M, (X,Y), flags=cv2.INTER_LINEAR) # 4. Get polinomial fit of lines # if > 4 frames skipped (or first frame, as skipped_frames is initialized to 100) do full search if skipped_frames > 5: fit_method = "Boxes" leftx, lefty, rightx, righty, out_img = find_lane_pixels(warped) else: fit_method = "Around fit" leftx, lefty, rightx, righty, out_img = find_lane_around_fit(warped, left_lane.fit_x, right_lane.fit_x) # fit polynomials and sanity check try: left_fit, right_fit, left_px, right_px, ploty = fit(leftx, lefty, rightx, righty, warped.shape[0]) detected, err_msg = sanity_chk(ploty, left_px, right_px) except: detected, err_msg = False, "Empty data" if detected: skipped_frames = 0 else: skipped_frames += 1 # 5. Calculate distance to center, curvature, and update Line objects if detected or (fit_method == "Boxes" and err_msg != "Empty data"): left_curv, right_curv = find_curv(ploty, left_fit, right_fit) left_lane.update(ploty, left_fit, left_px, left_curv) right_lane.update(ploty, right_fit, right_px, right_curv) lane_w = (right_lane.base_pos - left_lane.base_pos) * 3.7/700 offset = (((right_lane.base_pos + left_lane.base_pos) - img.shape[1]) / 2) * 3.7/700 # 6. Plot fitted lanes into original image # Create an image to draw the lines on warp_zero = np.zeros_like(warped).astype(np.uint8) color_warp = np.dstack((warp_zero, warp_zero, warp_zero)) # Recast the x and y points into usable format for cv2.fillPoly() pts_left = np.array([np.transpose(np.vstack([left_lane.fit_x, left_lane.fit_y]))]) pts_right = np.array([np.flipud(np.transpose(np.vstack([right_lane.fit_x, right_lane.fit_y])))]) pts = np.hstack((pts_left, pts_right)) # Draw the lane onto the warped blank image cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0)) # Warp the blank back to original image space using inverse perspective matrix (Minv) newwarp = cv2.warpPerspective(color_warp, Minv, (img.shape[1], img.shape[0])) # Combine the result with the original image result = cv2.addWeighted(undist, 1, newwarp, 0.3, 0) # if error save original img to check closely in image pipeline if 1 < skipped_frames < 3: mpimg.imsave(err_msg + "_" + str(error_im) + ".jpg", img) error_im += 1 # Add text road_curv = (left_lane.curv_avg + right_lane.curv_avg) // 2 if road_curv > 2000: road_curv_text = "Road curvature: straight" else: road_curv_text = "Road curvature: " + str(road_curv) + "m" side = {True: "left", False: "right"} offset_txt = "Car is {0:.2f}m {1:s} of center".format(offset, side[offset > 0]) for i, txt in enumerate([road_curv_text, offset_txt]): cv2.putText(result, txt, (75, 75 * (i+1)), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 3) # Uncomment for debugging messages # lane_width_txt = "Lane width: %.2f m" % lane_w # for i, obj, txt in [(1, left_lane, "Left"), (2, right_lane, "Right")]: # if obj.curv_avg > 2000: # curv_txt = txt + " curvature: straight" # else: # curv_txt = txt + " curvature: " + str(int(obj.curv_avg)) + "m" # cv2.putText(result,curv_txt, (550, 50 * i), cv2.FONT_HERSHEY_SIMPLEX, 1, 0, 2) # cv2.putText(result, "Skipped frames: " + str(skipped_frames), (550,150), cv2.FONT_HERSHEY_SIMPLEX, 1, 0, 2) # cv2.putText(result, fit_method, (550, 200), cv2.FONT_HERSHEY_SIMPLEX, 1, 0, 2) # if err_msg != "": # cv2.putText(result, "Error!: " + err_msg, (550, 250), cv2.FONT_HERSHEY_SIMPLEX, 1, 0, 2) return result # *** MAIN *** # define global variables to use in the pipeline left_lane = Line() right_lane = Line() error_im = 1 skipped_frames = 100 # load video clip_name = "challenge_video" clip1 = VideoFileClip(clip_name + ".mp4")#.subclip(0, 8) # run video through the pipeline and save output out_clip = clip1.fl_image(pipeline) out_clip.write_videofile("output_videos/" + clip_name + "_output.mp4", audio=False)
40.572368
113
0.65364
import numpy as np import pickle import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from moviepy.editor import VideoFileClip from image_thresholding import * from plotting_helpers import * from line_fit import * from Line import * def pipeline(img): global error_im, skipped_frames try: saved_dist = pickle.load(open('calibrate_camera.p', 'rb'), encoding='latin1') mtx = saved_dist['mtx'] dist = saved_dist['dist'] except (OSError, IOError): print("No saved distorsion data. Run camera_calibration.py") undist = cv2.undistort(img, mtx, dist, None, mtx) ksize = 3 gradx = abs_sobel_thresh(undist, orient='x', sobel_kernel=ksize, thresh=(10, 100)) grady = abs_sobel_thresh(undist, orient='y', sobel_kernel=ksize, thresh=(5, 100)) mag_bin = mag_thresh(undist, sobel_kernel=ksize, mag_thresh=(10, 200)) dir_bin = dir_threshold(undist, sobel_kernel=15, thresh=(0.9, 1.2)) hls_bin = hls_select(img, thresh=(50, 255)) white_bin = white_select(img, thresh=195) yellow_bin = yellow_select(img) combined = np.zeros_like(dir_bin) combined[((mag_bin == 1) & (dir_bin == 1) & (hls_bin == 1)) | ((white_bin == 1) | (yellow_bin == 1))] = 1 X = combined.shape[1] Y = combined.shape[0] src = np.float32( [[205, 720], [1075, 720], [700, 460], [580, 460]]) dst = np.float32( [[300, 720], [980, 720], [980, 0], [300, 0]]) M = cv2.getPerspectiveTransform(src, dst) Minv = cv2.getPerspectiveTransform(dst, src) warped = cv2.warpPerspective(combined, M, (X,Y), flags=cv2.INTER_LINEAR) if skipped_frames > 5: fit_method = "Boxes" leftx, lefty, rightx, righty, out_img = find_lane_pixels(warped) else: fit_method = "Around fit" leftx, lefty, rightx, righty, out_img = find_lane_around_fit(warped, left_lane.fit_x, right_lane.fit_x) try: left_fit, right_fit, left_px, right_px, ploty = fit(leftx, lefty, rightx, righty, warped.shape[0]) detected, err_msg = sanity_chk(ploty, left_px, right_px) except: detected, err_msg = False, "Empty data" if detected: skipped_frames = 0 else: skipped_frames += 1 if detected or (fit_method == "Boxes" and err_msg != "Empty data"): left_curv, right_curv = find_curv(ploty, left_fit, right_fit) left_lane.update(ploty, left_fit, left_px, left_curv) right_lane.update(ploty, right_fit, right_px, right_curv) lane_w = (right_lane.base_pos - left_lane.base_pos) * 3.7/700 offset = (((right_lane.base_pos + left_lane.base_pos) - img.shape[1]) / 2) * 3.7/700 warp_zero = np.zeros_like(warped).astype(np.uint8) color_warp = np.dstack((warp_zero, warp_zero, warp_zero)) pts_left = np.array([np.transpose(np.vstack([left_lane.fit_x, left_lane.fit_y]))]) pts_right = np.array([np.flipud(np.transpose(np.vstack([right_lane.fit_x, right_lane.fit_y])))]) pts = np.hstack((pts_left, pts_right)) cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0)) newwarp = cv2.warpPerspective(color_warp, Minv, (img.shape[1], img.shape[0])) result = cv2.addWeighted(undist, 1, newwarp, 0.3, 0) if 1 < skipped_frames < 3: mpimg.imsave(err_msg + "_" + str(error_im) + ".jpg", img) error_im += 1 road_curv = (left_lane.curv_avg + right_lane.curv_avg) // 2 if road_curv > 2000: road_curv_text = "Road curvature: straight" else: road_curv_text = "Road curvature: " + str(road_curv) + "m" side = {True: "left", False: "right"} offset_txt = "Car is {0:.2f}m {1:s} of center".format(offset, side[offset > 0]) for i, txt in enumerate([road_curv_text, offset_txt]): cv2.putText(result, txt, (75, 75 * (i+1)), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 3) return result left_lane = Line() right_lane = Line() error_im = 1 skipped_frames = 100 clip_name = "challenge_video" clip1 = VideoFileClip(clip_name + ".mp4") out_clip = clip1.fl_image(pipeline) out_clip.write_videofile("output_videos/" + clip_name + "_output.mp4", audio=False)
true
true
f7278a13c9265e6e8a34e3ea72f574bcebb85a0d
4,861
py
Python
src/Network/SR4DFlowNet.py
EdwardFerdian/4DFlowNet
e9c8bf72660b41ef5c7b6c677a71283ead32bbab
[ "MIT" ]
14
2020-06-17T04:28:39.000Z
2022-02-24T07:21:51.000Z
src/Network/SR4DFlowNet.py
EdwardFerdian/4DFlowNet
e9c8bf72660b41ef5c7b6c677a71283ead32bbab
[ "MIT" ]
null
null
null
src/Network/SR4DFlowNet.py
EdwardFerdian/4DFlowNet
e9c8bf72660b41ef5c7b6c677a71283ead32bbab
[ "MIT" ]
7
2020-08-13T03:21:31.000Z
2022-02-15T13:01:18.000Z
import tensorflow as tf class SR4DFlowNet(): def __init__(self, res_increase): self.res_increase = res_increase def build_network(self, u, v, w, u_mag, v_mag, w_mag, low_resblock=8, hi_resblock=4, channel_nr=64): channel_nr = 64 speed = (u ** 2 + v ** 2 + w ** 2) ** 0.5 mag = (u_mag ** 2 + v_mag ** 2 + w_mag ** 2) ** 0.5 pcmr = mag * speed phase = tf.keras.layers.concatenate([u,v,w]) pc = tf.keras.layers.concatenate([pcmr, mag, speed]) pc = conv3d(pc,3,channel_nr, 'SYMMETRIC', 'relu') pc = conv3d(pc,3,channel_nr, 'SYMMETRIC', 'relu') phase = conv3d(phase,3,channel_nr, 'SYMMETRIC', 'relu') phase = conv3d(phase,3,channel_nr, 'SYMMETRIC', 'relu') concat_layer = tf.keras.layers.concatenate([phase, pc]) concat_layer = conv3d(concat_layer, 1, channel_nr, 'SYMMETRIC', 'relu') concat_layer = conv3d(concat_layer, 3, channel_nr, 'SYMMETRIC', 'relu') # res blocks rb = concat_layer for i in range(low_resblock): rb = resnet_block(rb, "ResBlock", channel_nr, pad='SYMMETRIC') rb = upsample3d(rb, self.res_increase) # refinement in HR for i in range(hi_resblock): rb = resnet_block(rb, "ResBlock", channel_nr, pad='SYMMETRIC') # 3 separate path version u_path = conv3d(rb, 3, channel_nr, 'SYMMETRIC', 'relu') u_path = conv3d(u_path, 3, 1, 'SYMMETRIC', None) v_path = conv3d(rb, 3, channel_nr, 'SYMMETRIC', 'relu') v_path = conv3d(v_path, 3, 1, 'SYMMETRIC', None) w_path = conv3d(rb, 3, channel_nr, 'SYMMETRIC', 'relu') w_path = conv3d(w_path, 3, 1, 'SYMMETRIC', None) b_out = tf.keras.layers.concatenate([u_path, v_path, w_path]) return b_out def upsample3d(input_tensor, res_increase): """ Resize the image by linearly interpolating the input using TF '``'resize_bilinear' function. :param input_tensor: 2D/3D image tensor, with shape: 'batch, X, Y, Z, Channels' :return: interpolated volume Original source: https://niftynet.readthedocs.io/en/dev/_modules/niftynet/layer/linear_resize.html """ # We need this option for the bilinear resize to prevent shifting bug align = True b_size, x_size, y_size, z_size, c_size = input_tensor.shape x_size_new, y_size_new, z_size_new = x_size * res_increase, y_size * res_increase, z_size * res_increase if res_increase == 1: # already in the target shape return input_tensor # resize y-z squeeze_b_x = tf.reshape(input_tensor, [-1, y_size, z_size, c_size], name='reshape_bx') resize_b_x = tf.compat.v1.image.resize_bilinear(squeeze_b_x, [y_size_new, z_size_new], align_corners=align) resume_b_x = tf.reshape(resize_b_x, [-1, x_size, y_size_new, z_size_new, c_size], name='resume_bx') # Reorient reoriented = tf.transpose(resume_b_x, [0, 3, 2, 1, 4]) # squeeze and 2d resize squeeze_b_z = tf.reshape(reoriented, [-1, y_size_new, x_size, c_size], name='reshape_bz') resize_b_z = tf.compat.v1.image.resize_bilinear(squeeze_b_z, [y_size_new, x_size_new], align_corners=align) resume_b_z = tf.reshape(resize_b_z, [-1, z_size_new, y_size_new, x_size_new, c_size], name='resume_bz') output_tensor = tf.transpose(resume_b_z, [0, 3, 2, 1, 4]) return output_tensor def conv3d(x, kernel_size, filters, padding='SYMMETRIC', activation=None, initialization=None, use_bias=True): """ Based on: https://github.com/gitlimlab/CycleGAN-Tensorflow/blob/master/ops.py For tf padding, refer to: https://www.tensorflow.org/api_docs/python/tf/pad """ reg_l2 = tf.keras.regularizers.l2(5e-7) if padding == 'SYMMETRIC' or padding == 'REFLECT': p = (kernel_size - 1) // 2 x = tf.pad(x, [[0,0],[p,p],[p,p], [p,p],[0,0]], padding) x = tf.keras.layers.Conv3D(filters, kernel_size, activation=activation, kernel_initializer=initialization, use_bias=use_bias, kernel_regularizer=reg_l2)(x) else: assert padding in ['SAME', 'VALID'] x = tf.keras.layers.Conv3D(filters, kernel_size, activation=activation, kernel_initializer=initialization, use_bias=use_bias, kernel_regularizer=reg_l2)(x) return x def resnet_block(x, block_name='ResBlock', channel_nr=64, scale = 1, pad='SAME'): tmp = conv3d(x, kernel_size=3, filters=channel_nr, padding=pad, activation=None, use_bias=False, initialization=None) tmp = tf.keras.layers.LeakyReLU(alpha=0.2)(tmp) tmp = conv3d(tmp, kernel_size=3, filters=channel_nr, padding=pad, activation=None, use_bias=False, initialization=None) tmp = x + tmp * scale tmp = tf.keras.layers.LeakyReLU(alpha=0.2)(tmp) return tmp
40.173554
163
0.649866
import tensorflow as tf class SR4DFlowNet(): def __init__(self, res_increase): self.res_increase = res_increase def build_network(self, u, v, w, u_mag, v_mag, w_mag, low_resblock=8, hi_resblock=4, channel_nr=64): channel_nr = 64 speed = (u ** 2 + v ** 2 + w ** 2) ** 0.5 mag = (u_mag ** 2 + v_mag ** 2 + w_mag ** 2) ** 0.5 pcmr = mag * speed phase = tf.keras.layers.concatenate([u,v,w]) pc = tf.keras.layers.concatenate([pcmr, mag, speed]) pc = conv3d(pc,3,channel_nr, 'SYMMETRIC', 'relu') pc = conv3d(pc,3,channel_nr, 'SYMMETRIC', 'relu') phase = conv3d(phase,3,channel_nr, 'SYMMETRIC', 'relu') phase = conv3d(phase,3,channel_nr, 'SYMMETRIC', 'relu') concat_layer = tf.keras.layers.concatenate([phase, pc]) concat_layer = conv3d(concat_layer, 1, channel_nr, 'SYMMETRIC', 'relu') concat_layer = conv3d(concat_layer, 3, channel_nr, 'SYMMETRIC', 'relu') rb = concat_layer for i in range(low_resblock): rb = resnet_block(rb, "ResBlock", channel_nr, pad='SYMMETRIC') rb = upsample3d(rb, self.res_increase) for i in range(hi_resblock): rb = resnet_block(rb, "ResBlock", channel_nr, pad='SYMMETRIC') u_path = conv3d(rb, 3, channel_nr, 'SYMMETRIC', 'relu') u_path = conv3d(u_path, 3, 1, 'SYMMETRIC', None) v_path = conv3d(rb, 3, channel_nr, 'SYMMETRIC', 'relu') v_path = conv3d(v_path, 3, 1, 'SYMMETRIC', None) w_path = conv3d(rb, 3, channel_nr, 'SYMMETRIC', 'relu') w_path = conv3d(w_path, 3, 1, 'SYMMETRIC', None) b_out = tf.keras.layers.concatenate([u_path, v_path, w_path]) return b_out def upsample3d(input_tensor, res_increase): align = True b_size, x_size, y_size, z_size, c_size = input_tensor.shape x_size_new, y_size_new, z_size_new = x_size * res_increase, y_size * res_increase, z_size * res_increase if res_increase == 1: return input_tensor squeeze_b_x = tf.reshape(input_tensor, [-1, y_size, z_size, c_size], name='reshape_bx') resize_b_x = tf.compat.v1.image.resize_bilinear(squeeze_b_x, [y_size_new, z_size_new], align_corners=align) resume_b_x = tf.reshape(resize_b_x, [-1, x_size, y_size_new, z_size_new, c_size], name='resume_bx') reoriented = tf.transpose(resume_b_x, [0, 3, 2, 1, 4]) squeeze_b_z = tf.reshape(reoriented, [-1, y_size_new, x_size, c_size], name='reshape_bz') resize_b_z = tf.compat.v1.image.resize_bilinear(squeeze_b_z, [y_size_new, x_size_new], align_corners=align) resume_b_z = tf.reshape(resize_b_z, [-1, z_size_new, y_size_new, x_size_new, c_size], name='resume_bz') output_tensor = tf.transpose(resume_b_z, [0, 3, 2, 1, 4]) return output_tensor def conv3d(x, kernel_size, filters, padding='SYMMETRIC', activation=None, initialization=None, use_bias=True): reg_l2 = tf.keras.regularizers.l2(5e-7) if padding == 'SYMMETRIC' or padding == 'REFLECT': p = (kernel_size - 1) // 2 x = tf.pad(x, [[0,0],[p,p],[p,p], [p,p],[0,0]], padding) x = tf.keras.layers.Conv3D(filters, kernel_size, activation=activation, kernel_initializer=initialization, use_bias=use_bias, kernel_regularizer=reg_l2)(x) else: assert padding in ['SAME', 'VALID'] x = tf.keras.layers.Conv3D(filters, kernel_size, activation=activation, kernel_initializer=initialization, use_bias=use_bias, kernel_regularizer=reg_l2)(x) return x def resnet_block(x, block_name='ResBlock', channel_nr=64, scale = 1, pad='SAME'): tmp = conv3d(x, kernel_size=3, filters=channel_nr, padding=pad, activation=None, use_bias=False, initialization=None) tmp = tf.keras.layers.LeakyReLU(alpha=0.2)(tmp) tmp = conv3d(tmp, kernel_size=3, filters=channel_nr, padding=pad, activation=None, use_bias=False, initialization=None) tmp = x + tmp * scale tmp = tf.keras.layers.LeakyReLU(alpha=0.2)(tmp) return tmp
true
true
f7278a52cbb84e8828f86b3c9b2a793ccd2f5400
419
py
Python
clientes/forms.py
Etxea/gestion_eide_web
8a59be1ddb59a4713cb3346534fd01f643d8f924
[ "MIT" ]
null
null
null
clientes/forms.py
Etxea/gestion_eide_web
8a59be1ddb59a4713cb3346534fd01f643d8f924
[ "MIT" ]
null
null
null
clientes/forms.py
Etxea/gestion_eide_web
8a59be1ddb59a4713cb3346534fd01f643d8f924
[ "MIT" ]
null
null
null
from django import forms from django.forms import ModelForm from models import * from django.forms.models import inlineformset_factory class ClienteForm(forms.ModelForm): class Meta: model = Cliente class ClienteContactoForm(forms.ModelForm): class Meta: model = ClienteContacto exclude = ['cliente'] #ClienteContactoFormset = inlineformset_factory(Cliente, ClienteContacto)
24.647059
73
0.74463
from django import forms from django.forms import ModelForm from models import * from django.forms.models import inlineformset_factory class ClienteForm(forms.ModelForm): class Meta: model = Cliente class ClienteContactoForm(forms.ModelForm): class Meta: model = ClienteContacto exclude = ['cliente']
true
true
f7278a76375e3a6c0657a5bf9351de27906e9406
92,087
py
Python
xalpha/universal.py
kingmoon3/xalpha
dd877c6bce1b85a4facd38de9dc35a7bf0acf1c6
[ "MIT" ]
3
2021-08-15T10:00:14.000Z
2022-02-12T22:30:01.000Z
xalpha/universal.py
kingmoon3/xalpha
dd877c6bce1b85a4facd38de9dc35a7bf0acf1c6
[ "MIT" ]
null
null
null
xalpha/universal.py
kingmoon3/xalpha
dd877c6bce1b85a4facd38de9dc35a7bf0acf1c6
[ "MIT" ]
1
2021-10-01T13:12:10.000Z
2021-10-01T13:12:10.000Z
# -*- coding: utf-8 -*- """ modules for universal fetcher that gives historical daily data and realtime data for almost everything in the market """ import os import sys import time import datetime as dt import numpy as np import pandas as pd import logging import inspect from bs4 import BeautifulSoup from functools import wraps, lru_cache from uuid import uuid4 from sqlalchemy import exc from dateutil.relativedelta import relativedelta try: from jqdatasdk import ( get_index_weights, query, get_fundamentals, valuation, get_query_count, finance, get_index_stocks, macro, get_price, ) # 本地导入 except ImportError: try: from jqdata import finance, macro # 云平台导入 except ImportError: pass from xalpha.info import basicinfo, fundinfo, mfundinfo, get_fund_holdings from xalpha.indicator import indicator from xalpha.cons import ( rget, rpost, rget_json, rpost_json, tz_bj, last_onday, region_trans, today_obj, _float, ) from xalpha.provider import data_source from xalpha.exceptions import DataPossiblyWrong, ParserFailure pd.options.mode.chained_assignment = None # turn off setwith copy warning thismodule = sys.modules[__name__] xamodule = sys.modules["xalpha"] logger = logging.getLogger(__name__) def tomorrow_ts(): dto = dt.datetime.now() + dt.timedelta(1) return dto.timestamp() def has_weekday(start, end): for d in pd.date_range(start, end): if d.weekday() < 5: return True return False def ts2pdts(ts): dto = dt.datetime.fromtimestamp(ts / 1000, tz=tz_bj).replace(tzinfo=None) return dto.replace( hour=0, minute=0, second=0, microsecond=0 ) # 雪球美股数据时间戳是美国0点,按北京时区换回时间后,把时分秒扔掉就重合了 def decouple_code(code): """ decompose SH600000.A into SH600000, after :param code: :return: Tuple """ if len(code[1:].split(".")) > 1: # .SPI in US stock! type_ = code.split(".")[-1] code = ".".join(code.split(".")[:-1]) if type_.startswith("b") or type_.startswith("B"): type_ = "before" elif type_.startswith("a") or type_.startswith("A"): type_ = "after" elif type_.startswith("n") or type_.startswith("N"): type_ = "normal" else: logger.warning( "unrecoginzed flag for adjusted factor %s, use default" % type_ ) type_ = "before" else: type_ = "before" return code, type_ def lru_cache_time(ttl=None, maxsize=None): """ TTL support on lru_cache :param ttl: float or int, seconds :param maxsize: int, maxsize for lru_cache :return: """ def wrapper(func): # Lazy function that makes sure the lru_cache() invalidate after X secs @lru_cache(maxsize) def time_aware(_ttl, *args, **kwargs): return func(*args, **kwargs) setattr(thismodule, func.__name__ + "_ttl", time_aware) @wraps(func) def newfunc(*args, **kwargs): ttl_hash = round(time.time() / ttl) f_ttl = getattr(thismodule, func.__name__ + "_ttl") return f_ttl(ttl_hash, *args, **kwargs) return newfunc return wrapper # TODO: 缓存 token 的合适时间尺度 @lru_cache_time(ttl=300) def get_token(): """ 获取雪球的验权 token,匿名也可获取,而且似乎永远恒定(大时间范围内会改变) :return: """ r = rget("https://xueqiu.com", headers={"user-agent": "Mozilla"}) return r.cookies["xq_a_token"] def get_historical_fromxq(code, count, type_="before", full=False): """ :param code: :param count: :param type_: str. normal, before, after :param full: :return: """ url = "https://stock.xueqiu.com/v5/stock/chart/kline.json?symbol={code}&begin={tomorrow}&period=day&type={type_}&count=-{count}" if full: url += "&indicator=kline,pe,pb,ps,pcf,market_capital,agt,ggt,balance" # pe 是 TTM 数据 r = rget_json( url.format( code=code, tomorrow=int(tomorrow_ts() * 1000), count=count, type_=type_ ), cookies={"xq_a_token": get_token()}, headers={"user-agent": "Mozilla/5.0"}, ) df = pd.DataFrame(data=r["data"]["item"], columns=r["data"]["column"]) df["date"] = (df["timestamp"]).apply(ts2pdts) # reset hours to zero return df @lru_cache() def get_industry_fromxq(code): """ part of symbols has empty industry information :param code: :return: dict """ url = ( "https://xueqiu.com/stock/industry/stockList.json?code=%s&type=1&size=100" % code ) r = rget_json(url, cookies={"xq_a_token": get_token()}) return r def get_historical_fromcninvesting(curr_id, st_date, end_date, app=False): data = { "curr_id": curr_id, # "smlID": smlID, # ? but seems to be fixed with curr_id, it turns out it doesn't matter "st_date": st_date, # %Y/%m/%d "end_date": end_date, "interval_sec": "Daily", "sort_col": "date", "sort_ord": "DESC", "action": "historical_data", } if not app: # fetch from web api r = rpost( "https://cn.investing.com/instruments/HistoricalDataAjax", data=data, headers={ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)\ AppleWebKit/537.36 (KHTML, like Gecko)", "Host": "cn.investing.com", "X-Requested-With": "XMLHttpRequest", }, ) else: # fetch from app api r = rpost( "https://cnappapi.investing.com/instruments/HistoricalDataAjax", data=data, headers={ "Accept": "*/*", "Accept-Encoding": "gzip", "Accept-Language": "zh-cn", "Cache-Control": "no-cache", "Connection": "keep-alive", "User-Agent": "Investing.China/0.0.3 CFNetwork/1121.2.2 Darwin/19.3.0", "ccode": "CN", #'ccode_time': '1585551041.986028', "x-app-ver": "117", "x-meta-ver": "14", "x-os": "ios", "x-uuid": str(uuid4()), "Host": "cn.investing.com", "X-Requested-With": "XMLHttpRequest", }, ) s = BeautifulSoup(r.text, "lxml") dfdict = {} cols = [] for col in s.find_all("th"): dfdict[str(col.contents[0])] = [] cols.append(str(col.contents[0])) num_cols = len(cols) for i, td in enumerate(s.find_all("td")[:-5]): if cols[i % num_cols] == "日期": dfdict[cols[i % num_cols]].append( dt.datetime.strptime(str(td.string), "%Y年%m月%d日") ) else: dfdict[cols[i % num_cols]].append(str(td.string)) return pd.DataFrame(dfdict) def prettify(df): _map = { "日期": "date", "收盘": "close", "开盘": "open", "高": "high", "低": "low", "涨跌幅": "percent", "交易量": "volume", } df.rename(_map, axis=1, inplace=True) if len(df) > 1 and df.iloc[1]["date"] < df.iloc[0]["date"]: df = df[::-1] # df = df[["date", "open", "close", "high", "low", "percent"]] df1 = df[["date"]] for k in ["open", "close", "high", "low", "volume"]: if k in df.columns: df1[k] = df[k].apply(_float) df1["percent"] = df["percent"] return df1 def dstr2dobj(dstr): if len(dstr.split("/")) > 1: d_obj = dt.datetime.strptime(dstr, "%Y/%m/%d") elif len(dstr.split(".")) > 1: d_obj = dt.datetime.strptime(dstr, "%Y.%m.%d") elif len(dstr.split("-")) > 1: d_obj = dt.datetime.strptime(dstr, "%Y-%m-%d") else: d_obj = dt.datetime.strptime(dstr, "%Y%m%d") return d_obj @lru_cache(maxsize=1024) def get_investing_id(suburl, app=False): if not app: url = "https://cn.investing.com" else: url = "https://cnappapi.investing.com" if not suburl.startswith("/"): url += "/" url += suburl if not app: headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36" } else: headers = { "Accept": "*/*", "Accept-Encoding": "gzip", "Accept-Language": "zh-cn", "Cache-Control": "no-cache", "Connection": "keep-alive", "User-Agent": "Investing.China/0.0.3 CFNetwork/1121.2.2 Darwin/19.3.0", "ccode": "CN", #'ccode_time': '1585551041.986028', "x-app-ver": "117", "x-meta-ver": "14", "x-os": "ios", "x-uuid": str(uuid4()), "Host": "cn.investing.com", "X-Requested-With": "XMLHttpRequest", } r = rget( url, headers=headers, ) s = BeautifulSoup(r.text, "lxml") pid = s.find("span", id="last_last")["class"][-1].split("-")[1] return pid def _variate_ua(): last = 20 + np.random.randint(20) ua = [] ua.append( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko)" ) ua.append( "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1" ) choice = np.random.randint(2) return ua[choice][:last] @lru_cache_time(ttl=120, maxsize=128) def get_rmb(start=None, end=None, prev=360, currency="USD/CNY"): """ 获取人民币汇率中间价, 该 API 官网数据源,稳定性很差 :param start: :param end: :param prev: :param currency: :return: pd.DataFrame """ bl = ["USD", "EUR", "100JPY", "HKD", "GBP", "AUD", "NZD", "SGD", "CHF", "CAD"] al = [ "MYR", "RUB", "ZAR", "KRW", "AED", "SAR", "HUF", "PLN", "DKK", "SEK", "NOK", "TRY", "MXN", "THB", ] is_inverse = False if (currency[:3] in al) or (currency[4:] in bl): is_inverse = True currency = currency[4:] + "/" + currency[:3] url = "http://www.chinamoney.com.cn/ags/ms/cm-u-bk-ccpr/CcprHisNew?startDate={start_str}&endDate={end_str}&currency={currency}&pageNum=1&pageSize=300" if not end: end_obj = today_obj() else: end_obj = dstr2dobj(end) if not start: start_obj = end_obj - dt.timedelta(prev) else: start_obj = dstr2dobj(start) start_str = start_obj.strftime("%Y-%m-%d") end_str = end_obj.strftime("%Y-%m-%d") count = (end_obj - start_obj).days + 1 rl = [] # API 很奇怪,需要经常变 UA 才好用 headers = { "Referer": "http://www.chinamoney.com.cn/chinese/bkccpr/", "Origin": "http://www.chinamoney.com.cn", "Host": "www.chinamoney.com.cn", "X-Requested-With": "XMLHttpRequest", } if count <= 360: headers.update({"user-agent": _variate_ua()}) r = rpost_json( url.format(start_str=start_str, end_str=end_str, currency=currency), headers=headers, ) rl.extend(r["records"]) else: # data more than 1 year cannot be fetched once due to API limitation sepo_obj = end_obj sepn_obj = sepo_obj - dt.timedelta(360) # sep0_obj = end_obj - dt.timedelta(361) while sepn_obj > start_obj: # [sepn sepo] headers.update({"user-agent": _variate_ua()}) r = rpost_json( url.format( start_str=sepn_obj.strftime("%Y-%m-%d"), end_str=sepo_obj.strftime("%Y-%m-%d"), currency=currency, ), headers=headers, ) rl.extend(r["records"]) sepo_obj = sepn_obj - dt.timedelta(1) sepn_obj = sepo_obj - dt.timedelta(360) headers.update({"user-agent": _variate_ua()}) r = rpost_json( url.format( start_str=start_obj.strftime("%Y-%m-%d"), end_str=sepo_obj.strftime("%Y-%m-%d"), currency=currency, ), headers=headers, ) rl.extend(r["records"]) data = {"date": [], "close": []} for d in rl: data["date"].append(pd.Timestamp(d["date"])) data["close"].append(d["values"][0]) df = pd.DataFrame(data) df = df[::-1] df["close"] = pd.to_numeric(df["close"]) if is_inverse: df["close"] = 1 / df["close"] return df def get_fund(code): # 随意设置非空 path,防止嵌套缓存到 fundinfo if code[0] == "F": if code.startswith("F96"): return get_historical_from_ttjj_oversea(code) else: df = fundinfo(code[1:], path="nobackend", priceonly=True).price elif code[0] == "T": df = fundinfo(code[1:], path="nobackend", priceonly=True).price df["netvalue"] = df["totvalue"] elif code[0] == "M": df = mfundinfo(code[1:], path="nobackend").price else: raise ParserFailure("Unknown fund code %s" % code) df["close"] = df["netvalue"] return df[["date", "close"]] def get_historical_from_ttjj_oversea(code, start=None, end=None): if code.startswith("F"): code = code[1:] pagesize = ( dt.datetime.strptime(end, "%Y%m%d") - dt.datetime.strptime(start, "%Y%m%d") ).days + 1 r = rget_json( "http://overseas.1234567.com.cn/overseasapi/OpenApiHander.ashx?api=HKFDApi&m=MethodJZ&hkfcode={hkfcode}&action=2&pageindex=0&pagesize={pagesize}&date1={startdash}&date2={enddash}&callback=".format( hkfcode=get_hkfcode(code), pagesize=pagesize, startdash=start[:4] + "-" + start[4:6] + "-" + start[6:], enddash=end[:4] + "-" + end[4:6] + "-" + end[6:], ) ) datalist = {"date": [], "close": []} for dd in r["Data"]: datalist["date"].append(pd.to_datetime(dd["PDATE"])) datalist["close"].append(dd["NAV"]) df = pd.DataFrame(datalist) df = df[df["date"] <= end] df = df[df["date"] >= start] df = df.sort_values("date", ascending=True) return df def get_portfolio_fromttjj(code, start=None, end=None): startobj = dt.datetime.strptime(start, "%Y%m%d") endobj = dt.datetime.strptime(end, "%Y%m%d") if (endobj - startobj).days < 90: return None # note start is always 1.1 4.1 7.1 10.1 in incremental updates if code.startswith("F"): code = code[1:] r = rget("http://fundf10.eastmoney.com/zcpz_{code}.html".format(code=code)) s = BeautifulSoup(r.text, "lxml") table = s.find("table", class_="tzxq") df = pd.read_html(str(table))[0] df["date"] = pd.to_datetime(df["报告期"]) df["stock_ratio"] = df["股票占净比"].replace("---", "0%").apply(lambda s: _float(s[:-1])) df["bond_ratio"] = df["债券占净比"].replace("---", "0%").apply(lambda s: _float(s[:-1])) df["cash_ratio"] = df["现金占净比"].replace("---", "0%").apply(lambda s: _float(s[:-1])) # df["dr_ratio"] = df["存托凭证占净比"].replace("---", "0%").apply(lambda s: xa.cons._float(s[:-1])) df["assets"] = df["净资产(亿元)"] df = df[::-1] return df[["date", "stock_ratio", "bond_ratio", "cash_ratio", "assets"]] # this is the most elegant approach to dispatch get_daily, the definition can be such simple # you actually don't need to bother on start end blah, everything is taken care of by ``cahcedio`` @data_source("jq") def get_fundshare_byjq(code, **kws): code = _inverse_convert_code(code) df = finance.run_query( query(finance.FUND_SHARE_DAILY) .filter(finance.FUND_SHARE_DAILY.code == code) .filter(finance.FUND_SHARE_DAILY.date >= kws["start"]) .filter(finance.FUND_SHARE_DAILY.date <= kws["end"]) .order_by(finance.FUND_SHARE_DAILY.date) ) df["date"] = pd.to_datetime(df["date"]) df = df[["date", "shares"]] return df @lru_cache(maxsize=1024) def get_futu_id(code): r = rget("https://www.futunn.com/stock/{code}".format(code=code)) sind = r.text.find("securityId") futuid = r.text[sind : sind + 30].split("=")[1].split(";")[0].strip(" ").strip("'") sind = r.text.find("marketType") market = r.text[sind : sind + 30].split("=")[1].split(";")[0].strip().strip("''") return futuid, market def get_futu_historical(code, start=None, end=None): fid, market = get_futu_id(code) r = rget( "https://www.futunn.com/new-quote/kline?security_id={fid}&type=2&market_type={market}".format( fid=fid, market=market ) ) df = pd.DataFrame(r.json()["data"]["list"]) df["date"] = df["k"].map( lambda s: dt.datetime.fromtimestamp(s) .replace(hour=0, minute=0, second=0, microsecond=0) .replace(tzinfo=None) ) df["open"] = df["o"] / 1000 df["close"] = df["c"] / 1000 df["high"] = df["h"] / 1000 df["low"] = df["l"] / 1000 df["volume"] = df["v"] df = df.drop(["k", "t", "o", "c", "h", "l", "v"], axis=1) return df def get_historical_fromsp(code, start=None, end=None, region="us", **kws): """ 标普官网数据源 :param code: :param start: :param end: :param kws: :return: """ if code.startswith("SP"): code = code[2:] if len(code.split(".")) > 1: col = code.split(".")[1] code = code.split(".")[0] else: col = "1" start_obj = dt.datetime.strptime(start, "%Y%m%d") fromnow = (today_obj() - start_obj).days if fromnow < 300: flag = "one" elif fromnow < 1000: flag = "three" else: flag = "ten" url = "https://{region}.spindices.com/idsexport/file.xls?\ selectedModule=PerformanceGraphView&selectedSubModule=Graph\ &yearFlag={flag}YearFlag&indexId={code}".format( region=region, flag=flag, code=code ) r = rget( url, headers={ "sec-fetch-dest": "document", "sec-fetch-mode": "navigate", "sec-fetch-site": "same-origin", "sec-fetch-user": "?1", "upgrade-insecure-requests": "1", }, ) df = pd.read_excel(r.content, engine="xlrd") # print(df.iloc[:10]) df = df.iloc[6:] df = df.dropna() df["close"] = df["Unnamed: " + col] df["date"] = pd.to_datetime(df["Unnamed: 0"]) df = df[["date", "close"]] return df def get_historical_frombb(code, start=None, end=None, **kws): """ https://www.bloomberg.com/ 数据源, 试验性支持。 似乎有很严格的 IP 封禁措施, 且最新数据更新滞后,且国内会被 reset,似乎难以支持 T-1 净值预测。强烈建议从英为或雅虎能找到的标的,不要用彭博源,该 API 只能作为 last resort。 :param code: :param start: :param end: :param kws: :return: """ if code.startswith("BB-"): code = code[3:] # end_obj = dt.datetime.strptime(end, "%Y%m%d") start_obj = dt.datetime.strptime(start, "%Y%m%d") fromnow = (today_obj() - start_obj).days if fromnow < 20: years = "1_MONTH" elif fromnow < 300: years = "1_YEAR" else: years = "5_YEAR" url = "https://www.bloomberg.com/markets2/api/history/{code}/PX_LAST?\ timeframe={years}&period=daily&volumePeriod=daily".format( years=years, code=code ) r = rget_json( url, headers={ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko)", "referer": "https://www.bloomberg.com/quote/{code}".format(code=code), "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "same-origin", "accept": "*/*", }, ) df = pd.DataFrame(r[0]["price"]) df["close"] = df["value"] df["date"] = pd.to_datetime(df["dateTime"]) df = df[["date", "close"]] return df def get_historical_fromft(code, start, end, _type="indices"): """ finance times 数据 :param code: :param start: :param end: :return: """ if not code.isdigit(): code = get_ft_id(code, _type=_type) start = start.replace("/", "").replace("-", "") end = end.replace("/", "").replace("-", "") start = start[:4] + "/" + start[4:6] + "/" + start[6:] end = end[:4] + "/" + end[4:6] + "/" + end[6:] url = "https://markets.ft.com/data/equities/ajax/\ get-historical-prices?startDate={start}&endDate={end}&symbol={code}".format( code=code, start=start, end=end ) r = rget_json(url, headers={"user-agent": "Mozilla/5.0"}) b = BeautifulSoup(r["html"], "lxml") data = {"date": [], "open": [], "close": [], "high": [], "low": []} for i, td in enumerate(b.findAll("td")): if i % 6 == 0: s = td.find("span").string.split(",")[1:] s = ",".join(s) data["date"].append(dt.datetime.strptime(s, " %B %d, %Y")) elif i % 6 == 1: data["open"].append(_float(td.string)) elif i % 6 == 2: data["high"].append(_float(td.string)) elif i % 6 == 3: data["low"].append(_float(td.string)) elif i % 6 == 4: data["close"].append(_float(td.string)) df = pd.DataFrame(data) df = df.iloc[::-1] return df def get_historical_fromyh(code, start=None, end=None): """ 雅虎财经数据源,支持数据丰富,不限于美股。但存在部分历史数据缺失 NAN 或者周末进入交易日的现象,可能数据需要进一步清洗和处理。 :param code: :param start: :param end: :return: """ if code.startswith("YH-"): code = code[3:] start_obj = dt.datetime.strptime(start, "%Y%m%d") fromnow = (today_obj() - start_obj).days if fromnow < 20: range_ = "1mo" elif fromnow < 50: range_ = "3mo" elif fromnow < 150: range_ = "6mo" elif fromnow < 300: range_ = "1y" elif fromnow < 600: range_ = "2y" elif fromnow < 1500: range_ = "5y" else: range_ = "10y" url = "https://query1.finance.yahoo.com/v8\ /finance/chart/{code}?region=US&lang=en-US&includePrePost=false\ &interval=1d&range={range_}&corsDomain=finance.yahoo.com&.tsrc=finance".format( code=code, range_=range_ ) # 该 API 似乎也支持起止时间选择参数,period1=1427500800&period2=1585353600 # 也可直接从历史数据页面爬取: https://finance.yahoo.com/quote/CSGOLD.SW/history?period1=1427500800&period2=1585353600&interval=1d&filter=history&frequency=1d r = rget_json(url) data = {} datel = [] for t in r["chart"]["result"][0]["timestamp"]: t = dt.datetime.fromtimestamp(t) if t.second != 0: t -= dt.timedelta(hours=8) datel.append(t.replace(tzinfo=None, hour=0, minute=0, second=0, microsecond=0)) data["date"] = datel for k in ["close", "open", "high", "low"]: data[k] = r["chart"]["result"][0]["indicators"]["quote"][0][k] df = pd.DataFrame(data) return df def get_historical_fromzzindex(code, start, end=None): """ 中证指数源 :param code: :param start: :param end: :return: """ if code.startswith("ZZ"): code = code[2:] start_obj = dt.datetime.strptime(start, "%Y%m%d") fromnow = (today_obj() - start_obj).days if fromnow < 20: flag = "1%E4%B8%AA%E6%9C%88" elif fromnow < 60: flag = "3%E4%B8%AA%E6%9C%88" # 个月 elif fromnow < 200: flag = "1%E5%B9%B4" # 年 else: flag = "5%E5%B9%B4" r = rget_json( "http://www.csindex.com.cn/zh-CN/indices/index-detail/\ {code}?earnings_performance={flag}&data_type=json".format( code=code, flag=flag ), headers={ "Host": "www.csindex.com.cn", "Referer": "http://www.csindex.com.cn/zh-CN/indices/index-detail/{code}".format( code=code ), "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36", "X-Requested-With": "XMLHttpRequest", "Accept": "application/json, text/javascript, */*; q=0.01", }, ) df = pd.DataFrame(r) df["date"] = pd.to_datetime(df["tradedate"]) df["close"] = df["tclose"].apply(_float) return df[["date", "close"]] def get_historical_fromgzindex(code, start, end): """ 国证指数源 :param code: :param start: :param end: :return: """ if code.startswith("GZ"): code = code[2:] start = start[:4] + "-" + start[4:6] + "-" + start[6:] end = end[:4] + "-" + end[4:6] + "-" + end[6:] params = { "indexCode": code, "startDate": start, "endDate": end, "frequency": "Day", } r = rget_json( "http://hq.cnindex.com.cn/market/market/getIndexDailyDataWithDataFormat", params=params, ) df = pd.DataFrame(r["data"]["data"], columns=r["data"]["item"]) df["date"] = pd.to_datetime(df["timestamp"]) df = df[["date", "close", "open", "low", "high", "percent", "amount", "volume"]] # TODO: 是否有这些列不全的国证指数? df = df[::-1] return df def get_historical_fromhzindex(code, start, end): """ 华证指数源 :param code: :param start: :param end: :return: """ if code.startswith("HZ"): code = code[2:] r = rget_json( "http://www.chindices.com/index/values.val?code={code}".format(code=code) ) df = pd.DataFrame(r["data"]) df["date"] = pd.to_datetime(df["date"]) df = df[["date", "price", "pctChange"]] df.rename(columns={"price": "close", "pctChange": "percent"}, inplace=True) df = df[::-1] return df def get_historical_fromesunny(code, start=None, end=None): """ 易盛商品指数 :param code: eg. ESCI000201 :param start: just placeholder :param end: just placeholder :return: """ # code if code.startswith("ESCI"): code = code[4:] + ".ESCI" r = rget( "http://www.esunny.com.cn/chartES/csv/shareday/day_易盛指数_{code}.es".format( code=code ) ) data = [] for l in r.text.split("\n"): row = [s.strip() for s in l.split("|")] # 开 高 低 收 结 if len(row) > 1: data.append(row[:7]) df = pd.DataFrame( data, columns=["date", "open", "high", "low", "close", "settlement", "amount"] ) df["date"] = pd.to_datetime(df["date"]) for c in ["open", "high", "low", "close", "settlement", "amount"]: df[c] = df[c].apply(_float) return df def get_historical_fromycharts(code, start, end, category, metric): params = { "securities": "include:true,id:{code},,".format(code=code), "calcs": "include:true,id:{metric},,".format(metric=metric), "startDate": start, # %m/%d/%Y "endDate": end, # %m/%d/%Y "zoom": "custom", } r = rget_json( "https://ycharts.com/charts/fund_data.json", params=params, headers={ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)\ AppleWebKit/537.36 (KHTML, like Gecko)", "Host": "ycharts.com", "X-Requested-With": "XMLHttpRequest", "Referer": "https://ycharts.com/{category}/{code}/chart/".format( category=category, code=code ), "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-origin", }, ) df = pd.DataFrame( data=r["chart_data"][0][0]["raw_data"], columns=["timestamp", "close"] ) df["date"] = (df["timestamp"]).apply(ts2pdts) return df[["date", "close"]] @lru_cache() def get_bond_rates(rating, date=None): """ 获取各评级企业债的不同久期的预期利率 :param rating: str. eg AAA, AA-, N for 中国国债 :param date: %Y-%m-%d :return: """ rating = rating.strip() rating_uid = { "N": "2c9081e50a2f9606010a3068cae70001", # 国债 "AAA": "2c9081e50a2f9606010a309f4af50111", "AAA-": "8a8b2ca045e879bf014607ebef677f8e", "AA+": "2c908188138b62cd01139a2ee6b51e25", "AA": "2c90818812b319130112c279222836c3", "AA-": "8a8b2ca045e879bf014607f9982c7fc0", "A+": "2c9081e91b55cc84011be40946ca0925", "A": "2c9081e91e6a3313011e6d438a58000d", "A-": "8a8b2ca04142df6a014148ca880f3046", "A": "2c9081e91e6a3313011e6d438a58000d", "BBB+": "2c9081e91ea160e5011eab1f116c1a59", "BBB": "8a8b2ca0455847ac0145650780ad68fb", "BB": "8a8b2ca0455847ac0145650ba23b68ff", "B": "8a8b2ca0455847ac0145650c3d726901", } # 上边字典不全,非常欢迎贡献 :) def _fetch(date): r = rpost( "https://yield.chinabond.com.cn/cbweb-mn/yc/searchYc?\ xyzSelect=txy&&workTimes={date}&&dxbj=0&&qxll=0,&&yqqxN=N&&yqqxK=K&&\ ycDefIds={uid}&&wrjxCBFlag=0&&locale=zh_CN".format( uid=rating_uid.get(rating, rating), date=date ), ) return r if not date: date = dt.datetime.today().strftime("%Y-%m-%d") r = _fetch(date) while len(r.text.strip()) < 20: # 当天没有数据,非交易日 date = last_onday(date).strftime("%Y-%m-%d") r = _fetch(date) l = r.json()[0]["seriesData"] l = [t for t in l if t[1]] df = pd.DataFrame(l, columns=["year", "rate"]) return df def get_bond_rates_range(rating, duration=3, freq="W-FRI", start=None, end=None): l = [] if rating.startswith("B-"): rating = rating[2:] rs = rating.split(".") if len(rs) > 1: duration = float(rs[1]) rating = rs[0] for d in pd.date_range(start, end, freq=freq): df = get_bond_rates(rating, d.strftime("%Y-%m-%d")) l.append([d, df[df["year"] <= duration].iloc[-1]["rate"]]) return pd.DataFrame(l, columns=["date", "close"]) @data_source("jq") def get_macro(table, start, end, datecol="stat_year"): df = macro.run_query( query(getattr(macro, table)) .filter(getattr(getattr(macro, table), datecol) >= start) .filter(getattr(getattr(macro, table), datecol) <= end) .order_by(getattr(getattr(macro, table), datecol)) ) df[datecol] = pd.to_datetime(df[datecol]) df["date"] = df[datecol] return df def set_handler(method="daily", f=None): """ 为 ``get_daily``, ``get_bar`` 或 ``get_rt`` 设置 hook,优先按照函数 f 进行处理,若返回 None,再按一般情形处理 :param method: str. daily, rt, bar :param f: func, default None. :return: None """ setattr(thismodule, "get_" + method + "_handler", f) def _get_daily( code, start=None, end=None, prev=365, _from=None, wrapper=True, handler=True, **kws ): """ universal fetcher for daily historical data of literally everything has a value in market. 数据来源包括但不限于天天基金,雪球,英为财情,外汇局官网,聚宽,标普官网,bloomberg,雅虎财经,ycharts等。 :param code: str. 1. 对于沪深市场的股票,指数,ETF,LOF 场内基金,可转债和债券,直接使用其代码,主要开头需要包括 SH 或者 SZ。如果数字代码之后接 .A .B .N 分别代表后复权,前复权和不复权数据,不加后缀默认前复权。港股美股同理。 2. 对于香港市场的股票,指数,使用其数字代码,同时开头要添加 HK。 3. 对于美国市场的股票,指数,ETF 等,直接使用其字母缩写代码即可。 4. 对于人民币中间价数据,使用 "USD/CNY" 的形式,具体可能的值可在 http://www.chinamoney.com.cn/chinese/bkccpr/ 历史数据的横栏查询,注意日元需要用 100JPY/CNY. 5. 对于所有可以在 cn.investing.com 网站查到的金融产品,其代码可以是该网站对应的统一代码,或者是网址部分,比如 DAX 30 的概览页面为 https://cn.investing.com/indices/germany-30,那么对应代码即为 "indices/germany-30"。也可去网页 inspect 手动查找其内部代码(一般不需要自己做,推荐直接使用网页url作为 code 变量值),手动 inspect 加粗的实时价格,其对应的网页 span class 中的 pid 的数值即为内部代码。 6. 对于国内发行的基金,使用基金代码,同时开头添加 F。若想考虑分红使用累计净值,则开头添加 T。 7. 对于国内发行的货币基金,使用基金代码,同时开头添加 M。(全部按照净值数据处理) 8. 形如 peb-000807.XSHG 或 peb-SH000807 格式的数据,可以返回每周的指数估值情况,需要 enable 聚宽数据源方可查看。 9. 形如 iw-000807.XSHG 或 iw-SH000807 格式的数据,可以返回每月的指数成分股和实时权重,需要 enable 聚宽数据源方可查看。 10. 形如 fs-SH501018 格式的数据,可以返回指定场内基金每日份额,需要 enable 聚宽数据源方可查看。 11. 形如 SP5475707.2 格式的数据,可以返回标普官网相关指数的日线数据(最近十年),id 5475707 部分可以从相关指数 export 按钮获取的链接中得到,小数点后的部分代表保存的列数。参考链接:https://us.spindices.com/indices/equity/sp-global-oil-index. 若SPC开头,则从中国网站获取。 12. 形如 BB-FGERBIU:ID 格式的数据,对应网页 https://www.bloomberg.com/quote/FGERBIU:ID,可以返回彭博的数据(最近五年) 13. 形如 sw-801720 格式的数据,可以返回对应申万行业的历史数据情况,需要 enable 聚宽数据源方可查看。 14. 形如 teb-SH000300 格式的数据,返回每周指数盈利和净资产总值数据(单位:亿人民币元),需要 enbale 聚宽数据方可查看。 15. 形如 YH-CSGOLD.SW 格式的数据,返回雅虎财经标的日线数据(最近十年)。代码来自标的网页 url:https://finance.yahoo.com/quote/CSGOLD.SW。 16. 形如 FT-22065529 格式的数据或 FT-INX:IOM,可以返回 financial times 的数据,推荐直接用后者。前者数字代码来源,打开浏览器 network 监视,切换图标时间轴时,会新增到 https://markets.ft.com/data/chartapi/series 的 XHR 请求,其 request payload 里的 [elements][symbol] 即为该指数对应数字。 17. 形如 FTC-WTI+Crude+Oil 格式的数据,开头可以是 FTC, FTE, FTX, FTF, FTB, FTI 对应 ft.com 子栏目 commdities,equities,currencies,funds,bonds,indicies。其中 FTI 和 FT 相同。 18. 形如 mcy-MAC_AREA_UNEMPLOY 格式的数据,返回相应的宏观数据,需要聚宽数据源。mcy,mcq,mcm 代表年度,季度和月度的数据,code 为表名,可以参考 https://www.joinquant.com/help/api/help?name=macroData 19. 形如 ZZ000905,ZZH30533 的代码,代表中证官网的指数,ZZ 之后接指数代码,注意有些指数代码里可能包含 H,历史数据最大到近五年。 20. 形如 GZB30018, GZ399299 格式的数据,代表国证系列指数, GZ 之后接指数代码,代码可能包含更多字母。 21. 形如 ESCI000201 格式的数据,易盛商品指数系列,参考 http://www.esunny.com.cn/index.php?a=lists&catid=60。 22. 形如 pt-F100032 格式的数据,返回指定基金每季度股票债券和现金的持仓比例 23. 形如 yc-companies/DBP,yc-companies/DBP/price 格式的数据,返回ycharts股票、ETF数据,对应网页 https://ycharts.com/companies/DBP/price,最后部分为数据含义,默认price,可选:net_asset_value(仅ETF可用)、total_return_price、total_return_forward_adjusted_price、average_volume_30,历史数据限制五年内。 24. 形如 yc-indices/^SPGSCICO,yc-indices/^SPGSCICO/level 格式的数据,返回ycharts指数数据,对应网页 https://ycharts.com/indices/%5ESPGSCICO/level,最后部分为数据含义,默认level,可选:total_return_forward_adjusted_price,历史数据限制五年内。 25. 形如 HZ999001 HZ999005 格式的数据,代表了华证系列指数 http://www.chindices.com/indicator.html# 26. 形如 B-AA+.3 格式的数据,代表了 AA+ 企业债三年久期利率数据 (每周) 27. 形如 fu-00700.HK 或 fu-BA.US 格式的数据,代表了来自 https://www.futunn.com/stock/BA-US 的日线行情数据 :param start: str. "20200101", "2020/01/01", "2020-01-01" are all legal. The starting date of daily data. :param end: str. format is the same as start. The ending date of daily data. :param prev: Optional[int], default 365. If start is not specified, start = end-prev. :param _from: Optional[str]. 一般用户不需设定该选项。can be one of "xueqiu", "zjj", "investing", "tiantianjijin". Only used for debug to enforce data source. For common use, _from can be chosed automatically based on code in the run time. :param wrapper: bool. 一般用户不需设定该选项。 :param handler: bool. Default True. 若为 False,则 handler 钩子失效,用于钩子函数中的原函数嵌套调用。 :return: pd.Dataframe. must include cols: date[pd.Timestamp],close[float64]。 """ if handler: if getattr(thismodule, "get_daily_handler", None): args = inspect.getargvalues(inspect.currentframe()) f = getattr(thismodule, "get_daily_handler") fr = f(**args.locals) if fr is not None: return fr if not end: end_obj = today_obj() else: end_obj = dstr2dobj(end) if not start: start_obj = end_obj - dt.timedelta(days=prev) else: start_obj = dstr2dobj(start) if not _from: if (code.startswith("SH") or code.startswith("SZ")) and code[2:8].isdigit(): _from = "xueqiu" elif code.endswith("/CNY") or code.startswith("CNY/"): _from = "zjj" elif code.isdigit(): _from = "cninvesting" elif code[0] in ["F", "M", "T"] and code[1:].isdigit(): _from = "ttjj" elif code.startswith("HK") and code[2:7].isdigit(): _from = "xueqiu" code = code[2:] elif code.startswith("SP") and code[2:].split(".")[0].isdigit(): _from = "SP" elif code.startswith("SPC") and code[3:].split(".")[0].isdigit(): _from = "SPC" elif code.startswith("ZZ") and code[4:].isdigit(): # 注意中证系列指数的代码里可能包含字母! _from = "ZZ" elif code.startswith("GZ") and code[-3:].isdigit(): # 注意国证系列指数的代码里可能包含多个字母! _from = "GZ" elif code.startswith("HZ") and code[2:].isdigit(): _from = "HZ" elif code.startswith("ESCI") and code[4:].isdigit(): _from = "ES" elif code.startswith("yc-companies/") or code.startswith("yc-indices/"): _from = "ycharts" params = code.split("/") code = params[1] category = params[0].split("-")[1] if len(params) == 3: metric = params[2] else: if category == "companies": metric = "price" elif category == "indices": metric = "level" elif len(code.split("-")) >= 2 and len(code.split("-")[0]) <= 3: # peb-000807.XSHG _from = code.split("-")[0] code = "-".join(code.split("-")[1:]) elif len(code[1:].split("/")) == 2: _from = "cninvesting" code = get_investing_id(code) else: _from = "xueqiu" # 美股代码 count = (today_obj() - start_obj).days + 1 start_str = start_obj.strftime("%Y/%m/%d") end_str = end_obj.strftime("%Y/%m/%d") if _from in ["cninvesting", "investing", "default", "IN"]: df = get_historical_fromcninvesting(code, start_str, end_str) df = prettify(df) elif _from in ["xueqiu", "xq", "snowball", "XQ"]: code, type_ = decouple_code(code) df = get_historical_fromxq(code, count, type_=type_) df = prettify(df) elif _from in ["zhongjianjia", "zjj", "chinamoney", "ZJJ"]: df = get_rmb(start, end, prev, currency=code) elif _from in ["ttjj", "tiantianjijin", "xalpha", "eastmoney"]: if code.startswith("F96"): df = get_historical_from_ttjj_oversea(code, start=start, end=end) else: df = get_fund(code) elif _from == "peb": if ( code.startswith("SH000") or code.startswith("SZ399") or code.startswith("399") or code.startswith("000") ): df = _get_peb_range(code=code, start=start_str, end=end_str) elif code.startswith("F"): df = get_fund_peb_range(code=code, start=start, end=end) else: df = get_stock_peb_range(code=code, start=start, end=end, wrapper=True) elif _from == "iw": df = _get_index_weight_range(code=code, start=start_str, end=end_str) elif _from == "fs": df = get_fundshare_byjq(code, start=start, end=end) elif _from == "SP": df = get_historical_fromsp(code, start=start, end=end) elif _from == "SPC": df = get_historical_fromsp(code[3:], start=start, end=end, region="chinese") elif _from == "BB": df = get_historical_frombb(code, start=start, end=end) elif _from == "ZZ": df = get_historical_fromzzindex(code, start=start, end=end) elif _from == "GZ": df = get_historical_fromgzindex(code, start=start, end=end) elif _from == "HZ": df = get_historical_fromhzindex(code, start=start, end=end) elif _from == "ES": df = get_historical_fromesunny(code, start=start, end=end) elif _from == "B": df = get_bond_rates_range(code, start=start, end=end) elif _from == "fu": code = code.replace(".", "-") df = get_futu_historical(code, start=start, end=end) elif _from == "ycharts": df = get_historical_fromycharts( code, start=start_obj.strftime("%m/%d/%Y"), end=end_obj.strftime("%m/%d/%Y"), category=category, metric=metric, ) elif _from == "sw": df = get_sw_from_jq(code, start=start, end=end) elif _from == "teb": df = get_teb_range(code, start=start, end=end) elif _from in ["pt", "portfolio"]: df = get_portfolio_fromttjj(code, start=start, end=end) elif _from == "YH": df = get_historical_fromyh(code, start=start, end=end) elif _from in ["FT", "FTI"]: df = get_historical_fromft(code, start=start, end=end) elif _from == "FTE": df = get_historical_fromft(code, start=start, end=end, _type="equities") elif _from == "FTB": df = get_historical_fromft(code, start=start, end=end, _type="bonds") elif _from == "FTF": df = get_historical_fromft(code, start=start, end=end, _type="funds") elif _from == "FTX": df = get_historical_fromft(code, start=start, end=end, _type="currencies") elif _from == "FTC": df = get_historical_fromft(code, start=start, end=end, _type="commodities") elif _from == "INA": # investing app code = get_investing_id(code, app=True) df = get_historical_fromcninvesting(code, start_str, end_str, app=True) df = prettify(df) elif _from == "mcy": df = get_macro(code, start=start[:4], end=end[:4], datecol="stat_year") elif _from == "mcq": df = get_macro(code, start=start, end=end, datecol="stat_quarter") elif _from == "mcm": df = get_macro(code, start=start, end=end, datecol="stat_month") elif _from == "mcd": df = get_macro(code, start=start, end=end, datecol="day") else: raise ParserFailure("no such data source: %s" % _from) if wrapper or len(df) == 0: return df else: df = df[df.date <= end_str] df = df[df.date >= start_str] return df def get_xueqiu_rt(code, token="a664afb60c7036c7947578ac1a5860c4cfb6b3b5"): if code.startswith("HK") and code[2:].isdigit(): code = code[2:] url = "https://stock.xueqiu.com/v5/stock/quote.json?symbol={code}&extend=detail" r = rget_json( url.format(code=code), cookies={"xq_a_token": token}, headers={"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)"}, ) n = r["data"]["quote"]["name"] q = r["data"]["quote"]["current"] try: q = _float(q) except TypeError: # 针对雪球实时在9点后开盘前可能出现其他情形的fixup, 效果待 check # 现在的怀疑是在9am 到9:15 am, 雪球 API current 字段返回 Null q = _float(r["data"]["quote"]["last_close"]) q_ext = r["data"]["quote"].get("current_ext", None) percent = r["data"]["quote"]["percent"] try: percent = _float(percent) except: pass currency = r["data"]["quote"]["currency"] market = r["data"]["market"]["region"] timestr = dt.datetime.fromtimestamp(r["data"]["quote"]["time"] / 1000).strftime( "%Y-%m-%d %H:%M:%S" ) if r["data"]["quote"].get("timestamp_ext", None): time_ext = dt.datetime.fromtimestamp( r["data"]["quote"]["timestamp_ext"] / 1000 ).strftime("%Y-%m-%d %H:%M:%S") else: time_ext = None share = r["data"]["quote"]["total_shares"] fshare = r["data"]["quote"]["float_shares"] volume = r["data"]["quote"]["volume"] return { "name": n, "current": q, "percent": percent, "current_ext": _float(q_ext) if q_ext else None, "currency": currency, "market": market, # HK, US, CN "time": timestr, "time_ext": time_ext, "totshare": share, "floatshare": fshare, "volume": volume, } def get_cninvesting_rt(suburl, app=False): if not app: url = "https://cn.investing.com" else: url = "https://cnappapi.investing.com" if not suburl.startswith("/"): url += "/" url += suburl if not app: headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36" } else: headers = { "Accept": "*/*", "Accept-Encoding": "gzip", "Accept-Language": "zh-cn", "Cache-Control": "no-cache", "Connection": "keep-alive", "User-Agent": "Investing.China/0.0.3 CFNetwork/1121.2.2 Darwin/19.3.0", "ccode": "CN", #'ccode_time': '1585551041.986028', "x-app-ver": "117", "x-meta-ver": "14", "x-os": "ios", "x-uuid": str(uuid4()), "Host": "cn.investing.com", "X-Requested-With": "XMLHttpRequest", } r = rget( url, headers=headers, ) s = BeautifulSoup(r.text, "lxml") last_last = s.find("span", id="last_last") q = _float(last_last.string) name = s.find("h1").string.strip() ind = 0 timestr = s.select('span[class*="ClockBigIcon"]+span')[0].text l = s.find("div", class_="lighterGrayFont").contents for i, c in enumerate(l): if isinstance(c, str) and c.strip() == "货币": ind = i break if ind == 0: currency = None else: currency = l[ind - 1].string percent = _float( s.find("span", attrs={"dir": "ltr", "class": "parentheses"}).string[:-1] ) panhou = s.find("div", class_="afterHoursInfo") if panhou: q_ext = _float(panhou.find("span").string) else: q_ext = None market = None for span in s.findAll("span", class_="elp"): if span.find("a") and span.find("a")["href"].startswith("/markets"): market = span.string market = region_trans.get(market, market) time_ext = s.select("div[class~=lastUpdated]") if time_ext: time_ext = time_ext[0].text.strip() else: time_ext = None d = { "name": name, "current": q, "current_ext": q_ext, "time": timestr, "time_ext": time_ext, "currency": currency, "percent": percent, "market": market, } if suburl.startswith("commodities"): # 商品期货展期日 try: d["rollover"] = s.select("span[class*=float_lang_base_2]")[10].string d["lastrollover"] = s.select("span[class*=float_lang_base_2]")[13].string except (ValueError, IndexError, AttributeError): logger.warning("%s cannot extract rollover date" % suburl) # in case some commodities with strong page structure return d def get_rt_from_sina(code): if ( code.startswith("SH") or code.startswith("SZ") or code.startswith("HK") ) and code[2:].isdigit(): tinycode = code[:2].lower() + code[2:] if code.startswith("HK"): # 港股额外要求实时 tinycode = "rt_" + tinycode else: # 美股 tinycode = "gb_" if code.startswith("."): code = code[1:] tinycode += code.lower() r = rget("https://hq.sinajs.cn/list={tinycode}".format(tinycode=tinycode)) l = r.text.split("=")[1].split(",") d = {} d["name"] = l[0].strip('"') if ( code.startswith("SH") or code.startswith("SZ") or code.startswith("HK") ) and code[2:].isdigit(): # TODO: 20200819: API seems changed a bit, index shift? # or things may get zero when the market is closed? if code.startswith("HK"): d["current"] = float(l[9]) # 英文股票名称占位 d["currency"] = "HKD" d["percent"] = round(float(l[8]), 2) d["market"] = "HK" d["time"] = l[17] + " " + l[18] d["current_ext"] = None else: # A 股 d["current"] = float(l[3]) d["currency"] = "CNY" d["percent"] = round((float(l[3]) / float(l[2]) - 1) * 100, 2) d["market"] = "CN" d["time"] = l[-4] + " " + l[-3] for i in range(10, 19)[::2]: d["buy" + str(int((i - 8) / 2))] = (l[i + 1], l[i]) for i in range(20, 29)[::2]: d["sell" + str(int((i - 18) / 2))] = (l[i + 1], l[i]) d["current_ext"] = None else: d["currency"] = "USD" d["current"] = float(l[1]) d["percent"] = float(l[2]) d["current_ext"] = _float(l[21]) if _float(l[21]) > 0 else None d["market"] = "US" d["time"] = l[3] return d def make_ft_url(code, _type="indices"): """ :param code: :param _type: indices, commodities, currencies, funds, equities, bonds :return: """ if _type == "indices": url = "https://markets.ft.com/data/indices/tearsheet/summary?s={code}".format( code=code ) elif _type == "commodities": url = ( "https://markets.ft.com/data/commodities/tearsheet/summary?c={code}".format( code=code ) ) elif _type == "currencies": url = ( "https://markets.ft.com/data/currencies/tearsheet/summary?s={code}".format( code=code ) ) elif _type == "funds": url = "https://markets.ft.com/data/funds/tearsheet/summary?s={code}".format( code=code ) elif _type == "equities": url = "https://markets.ft.com/data/equities/tearsheet/summary?s={code}".format( code=code ) elif _type == "bonds": url = "https://markets.ft.com/data/bonds/tearsheet/summary?s={code}".format( code=code ) else: raise ParserFailure("no reconginzed type for ft datasource: %s" % _type) return url @lru_cache(maxsize=1024) def get_ft_id(code, _type="indices"): url = make_ft_url(code, _type=_type) r = rget(url) b = BeautifulSoup(r.text, "lxml") return eval( b.find("section", class_="mod-tearsheet-add-to-watchlist")["data-mod-config"] )["xid"] def get_rt_from_ft(code, _type="indices"): url = make_ft_url(code, _type=_type) r = rget(url) b = BeautifulSoup(r.text, "lxml") d = {} d["name"] = b.find("h1").string d["current"] = _float(b.find("span", class_="mod-ui-data-list__value").string) d["percent"] = _float( b.select("span[class^='mod-format--']")[0].text.split("/")[-1].strip()[:-1] ) d["current_ext"] = None d["market"] = None d["currency"] = b.find("span", class_="mod-ui-data-list__label").string.split("(")[ 1 ][:-1] d["time"] = b.find("div", class_="mod-disclaimer").string return d def get_rt_from_ycharts(code): if code.startswith("yc-"): code = code[3:] url = "https://ycharts.com/" + code r = rget(url) s = BeautifulSoup(r.text, "lxml") qdiv = s.select("div.index-rank.col-auto") # current spans = [s for s in qdiv[0].contents if s != "\n" and s.contents] d = {} d["name"] = s.select("h1,h3[class=securityName]")[0].text.strip() d["current"], d["percent"] = ( _float(spans[0].string), # current, _float(spans[1].contents[-2].string[1:-1]), # percent ) l = [ c.strip() for c in s.select("span[class=index-info]")[0].string.split("\n") if c.strip() ] d["time"] = l[1] d["currency"] = l[0].split(" ")[0].strip() d["market"] = None return d @lru_cache_time(ttl=300, maxsize=512) def get_newest_netvalue(code): """ 防止天天基金总量 API 最新净值更新不及时,获取基金最新公布净值及对应日期, depracated, use get_rt("F501018") instead :param code: six digits string for fund. :return: netvalue, %Y-%m-%d """ code = code[1:] r = rget("http://fund.eastmoney.com/{code}.html".format(code=code)) s = BeautifulSoup(r.text, "lxml") return ( float( s.findAll("dd", class_="dataNums")[1] .find("span", class_="ui-font-large") .string ), str(s.findAll("dt")[1]).split("(")[1].split(")")[0][7:], ) @lru_cache(maxsize=512) def get_hkfcode(code): if code.startswith("F"): code = code[1:] page = rget("http://overseas.1234567.com.cn/{code}".format(code=code)).text page.find("hkfcode") hkfcode = ( page[page.find("hkfcode") :] .split("=")[1] .split(";")[0] .lstrip() .lstrip("'") .strip("'") ) return hkfcode def get_rt_from_ttjj_oversea(code): if code.startswith("F"): code = code[1:] if not code.startswith("96"): raise ValueError("%s is not an oversea fund" % code) r = rget("http://overseas.1234567.com.cn/{code}.html".format(code=code)) r.encoding = "utf-8" s = BeautifulSoup(r.text, "lxml") start = s.select("dl.dataItem02")[0].text start = start.split("(")[1].split(")")[0] name = s.select("div[class='fundDetail-tit']")[0].text.split("(")[0].strip() name = name.split("(")[0].strip() value = _float(s.select("span.ui-font-large.ui-num")[0].text) date = ( s.select("dl[class='dataItem01']")[0] .find("p") .text.split("(")[-1] .split(")")[0] ) infol = [ r for r in s.select("div[class='infoOfFund']")[0].text.split("\n") if r.strip() ] return { "name": name, "time": date, "current": value, "market": "CN", "currency": None, # 很可能存在非人民币计价的互认基金 "current_ext": None, "type": infol[0].split(":")[1].strip(), "scale": infol[1].split(":")[1].strip(), "manager": infol[2].split(":")[1].strip(), "startdate": start, } @lru_cache_time(ttl=600, maxsize=512) def get_rt_from_ttjj(code): code = code[1:] if code.startswith("96"): return get_rt_from_ttjj_oversea(code) r = rget("http://fund.eastmoney.com/{code}.html".format(code=code)) r.encoding = "utf-8" s = BeautifulSoup(r.text, "lxml") name = s.select("div[style='float: left']")[0].text.split("(")[0] if s.findAll("dd", class_="dataNums")[1].find( "span", class_="ui-font-large" ): # 非货币基金 value, date = ( float( s.findAll("dd", class_="dataNums")[1] .find("span", class_="ui-font-large") .string ), str(s.findAll("dt")[1]).split("(")[1].split(")")[0][7:], ) estimate = s.select("span[id=gz_gsz]")[0].text # after loading if estimate == "--": gsz = rget( "http://fundgz.1234567.com.cn/js/{code}.js".format(code=code), headers={ "Host": "fundgz.1234567.com.cn", "Referer": "http://fund.eastmoney.com/", }, ) try: # in case eval error gsz_dict = eval(gsz.text[8:-2]) estimate = _float(gsz_dict["gsz"]) estimate_time = gsz_dict["gztime"] except: estimate = None else: try: estimate = _float(estimate) except ValueError: logger.warning("unrecognized estimate netvalue %s" % estimate) estimate = None else: value, date = ( s.findAll("dd", class_="dataNums")[1].text, str(s.findAll("dt")[1]).split("(")[1].split(")")[0], ) estimate = None status = s.select("span[class='staticCell']")[0].text.strip() tb = s.select("div.infoOfFund > table >tr>td") infol = [i.text for i in tb] try: estimate_time except NameError: estimate_time = None return { "name": name, "time": date, "current": value, "market": "CN", "currency": "CNY", "current_ext": None, "status": status, "type": infol[0].split(":")[1].split("\xa0")[0], "scale": infol[1].split(":")[1], "manager": infol[2].split(":")[1], "company": infol[4].split(":")[1], "estimate": estimate, "estimate_time": estimate_time, } # 是否有美元份额计价的基金会出问题? @lru_cache(2048) def get_fund_type(code): """ given fund code, return unified fund category which is extracted from get_rt(code)["type"] :param code: :return: str. """ code = code[-6:] t = get_rt("F" + code)["type"] if t in ["联接基金", "股票指数"] or t.startswith("ETF"): return "指数基金" elif t.startswith("QDII"): return "QDII" elif t.startswith("股票"): return "股票基金" elif t.startswith("混合"): return "混合基金" elif t.startswith("债券"): return "债券基金" elif t.startswith("货币"): return "货币基金" else: return "其他" def get_rt( code, _from=None, double_check=False, double_check_threhold=0.005, handler=True ): """ universal fetcher for realtime price of literally everything. :param code: str. 规则同 :func:`get_daily`. 需要注意场外基金和外汇中间价是不支持实时行情的,因为其每日只有一个报价。对于 investing 的数据源,只支持网址格式代码。 :param _from: Optional[str]. can be one of "xueqiu", "investing". Only used for debug to enfore data source. For common use, _from can be chosed automatically based on code in the run time. :param double_check: Optional[bool], default False. 如果设为 True,只适用于 A 股,美股,港股实时行情,会通过至少两个不同的数据源交叉验证,确保正确。 适用于需要自动交易等情形,防止实时数据异常。 :param handler: bool. Default True. 若为 False,则 handler 钩子失效,用于钩子函数中的嵌套。 :return: Dict[str, Any]. 包括 "name", "current", "percent" 三个必有项和 "current_ext"(盘后价格), "currency" (计价货币), "market" (发行市场), "time"(记录时间) 可能为 ``None`` 的选项。 """ # 对于一些标的,get_rt 的主任务可能不是 current 价格,而是去拿 market currency 这些元数据 # 现在用的新浪实时数据源延迟严重, double check 并不靠谱,港股数据似乎有15分钟延迟(已解决) # 雪球实时和新浪实时在9:00之后一段时间可能都有问题 # FT 数据源有10到20分钟的延迟 if handler: if getattr(thismodule, "get_rt_handler", None): args = inspect.getargvalues(inspect.currentframe()) f = getattr(thismodule, "get_rt_handler") fr = f(**args.locals) if fr: return fr if not _from: # if code.startswith("HK") and code[2:].isdigit(): # _from = "xueqiu" if code.startswith("yc-"): _from = "ycharts" elif len(code.split("-")) >= 2 and len(code.split("-")[0]) <= 3: _from = code.split("-")[0] code = "-".join(code.split("-")[1:]) elif (code.startswith("F") or code.startswith("T")) and code[1:].isdigit(): _from = "ttjj" elif len(code.split("/")) > 1: _from = "investing" else: # 默认启用雪球实时,新浪纯指数行情不完整 _from = "xueqiu" if _from in ["cninvesting", "investing"]: try: return get_cninvesting_rt(code) except Exception as e: logger.warning( "Fails due to %s, now trying app source of investing.com" % e.args[0] ) return get_cninvesting_rt(code, app=True) elif double_check and _from in ["xueqiu", "sina"]: r1 = get_xueqiu_rt(code, token=get_token()) r2 = get_rt_from_sina(code) if abs(r1["current"] / r2["current"] - 1) > double_check_threhold: raise DataPossiblyWrong("realtime data unmatch for %s" % code) return r2 elif _from in ["xueqiu", "xq", "snowball"]: try: return get_xueqiu_rt(code, token=get_token()) except (IndexError, ValueError, AttributeError, TypeError) as e: # 默认雪球实时引入备份机制 logging.warning( "Fails due to %s, now trying backup data source from sina" % e.args[0] ) return get_rt_from_sina(code) elif _from in ["sina", "sn", "xinlang"]: try: return get_rt_from_sina(code) except (IndexError, ValueError, AttributeError, TypeError) as e: # 默认雪球实时引入备份机制 logging.warning( "Fails due to %s, now trying backup data source from xueqiu" % e.args[0] ) return get_xueqiu_rt(code, token=get_token()) elif _from in ["ttjj"]: return get_rt_from_ttjj(code) elif _from in ["FT", "ft", "FTI"]: return get_rt_from_ft(code) elif _from == "FTE": return get_rt_from_ft(code, _type="equities") elif _from == "FTB": return get_rt_from_ft(code, _type="bonds") elif _from == "FTF": return get_rt_from_ft(code, _type="funds") elif _from == "FTX": return get_rt_from_ft(code, _type="currencies") elif _from == "FTC": return get_rt_from_ft(code, _type="commodities") elif _from in ["INA"]: # investing app return get_cninvesting_rt(code, app=True) elif _from in ["yc", "ycharts"]: return get_rt_from_ycharts(code) else: raise ParserFailure("unrecoginzed _from for %s" % _from) get_realtime = get_rt get_now = get_rt _cached_data = {} def reset_cache(): """ clear all cache of daily data in memory. :return: None. """ global _cached_data _cached_data = {} setattr(thismodule, "cached_dict", {}) def cached(s): """ **Deprecated**, use :func:`cachedio` instead, where ``backend="memory"``. Usage as follows: .. code-block:: python @cached("20170101") def get_daily(*args, **kws): return xa.get_daily(*args, **kws) Automatically cache the result in memory and avoid refetching :param s: str. eg. "20160101", the starting date of cached table. :return: wrapped function. """ def cached_start(f): @wraps(f) def wrapper(*args, **kws): print("cached function is deprecated, please instead use cachedio") if args: code = args[0] else: code = kws.get("code") start = kws.get("start", None) end = kws.get("end", None) prev = kws.get("prev", None) if not prev: prev = 365 if not end: end_obj = today_obj() else: end_obj = dstr2dobj(end) if not start: start_obj = end_obj - dt.timedelta(prev) else: start_obj = dstr2dobj(start) start_str = start_obj.strftime("%Y%m%d") end_str = end_obj.strftime("%Y%m%d") kws["start"] = s kws["end"] = dt.datetime.now().strftime("%Y%m%d") global _cached_data _cached_data.setdefault(s, {}) if code not in _cached_data[s]: df = f(*args, **kws) # print("cached %s" % code) _cached_data[s][code] = df else: pass # print("directly call cache") df = _cached_data[s][code] df = df[df["date"] <= end_str] df = df[df["date"] >= start_str] return df return wrapper return cached_start def cachedio(**ioconf): """ 用法类似:func:`cached`,通用透明缓存器,用来作为 (code, start, end ...) -> pd.DataFrame 形式函数的缓存层, 避免重复爬取已有数据。 :param **ioconf: 可选关键字参数 backend: csv or sql or memory, path: csv 文件夹或 sql engine, refresh True 会刷新结果,重新爬取, default False, prefix 是 key 前统一部分, 缓存 hash 标志 :return: """ def cached(f): @wraps(f) def wrapper(*args, **kws): if args: code = args[0] else: code = kws.get("code") date = ioconf.get("date", "date") # 没利用上这个栏的名字变化 precached = ioconf.get("precached", None) precached = kws.get("precached", precached) key = kws.get("key", code) key = key.replace("/", " ") key_func = ioconf.get("key_func", None) key_func = ioconf.get("keyfunc", key_func) if key_func is not None: key = key_func(key) defaultend = ioconf.get("defaultend", today_obj) defaultend = ioconf.get("default_end", defaultend) defaultprev = ioconf.get("defaultprev", 365) defaultprev = ioconf.get("default_prev", defaultprev) if isinstance(defaultend, str): defaultend = defaultend.replace("/", "").replace("-", "") defaultend = dt.datetime.strptime(defaultend, "%Y%m%d") if callable(defaultend): defaultend = defaultend() start = kws.get("start", None) end = kws.get("end", None) prev = kws.get("prev", None) prefix = ioconf.get("prefix", "") key = prefix + key if precached: precached = precached.replace("/", "").replace("-", "") precached_obj = dt.datetime.strptime(precached, "%Y%m%d") if not prev: prev = defaultprev if not end: end_obj = defaultend else: end_obj = dt.datetime.strptime( end.replace("/", "").replace("-", ""), "%Y%m%d" ) if not start: start_obj = end_obj - dt.timedelta(days=prev) else: start_obj = dt.datetime.strptime( start.replace("/", "").replace("-", ""), "%Y%m%d" ) start_str = start_obj.strftime("%Y%m%d") end_str = end_obj.strftime("%Y%m%d") backend = ioconf.get("backend") backend = kws.get("backend", backend) # if backend == "sql": # reserved for case insensitive database settings # key = key.lower() refresh = ioconf.get("refresh", False) refresh = kws.get("refresh", refresh) fetchonly = ioconf.get("fetchonly", False) fetchonly = ioconf.get("fetch_only", fetchonly) fetchonly = kws.get("fetchonly", fetchonly) fetchonly = kws.get("fetch_only", fetchonly) path = ioconf.get("path") path = kws.get("path", path) kws["start"] = start_str kws["end"] = end_str if not backend: df = f(*args, **kws) df = df[df["date"] <= kws["end"]] df = df[df["date"] >= kws["start"]] return df else: if backend == "csv": key = key + ".csv" if not getattr(thismodule, "cached_dict", None): setattr(thismodule, "cached_dict", {}) if refresh: is_changed = True df0 = f(*args, **kws) else: # non refresh try: if backend == "csv": if key in getattr(thismodule, "cached_dict"): # 即使硬盘级别的缓存,也有内存层,加快读写速度 df0 = getattr(thismodule, "cached_dict")[key] else: df0 = pd.read_csv(os.path.join(path, key)) elif backend == "sql": if key in getattr(thismodule, "cached_dict"): df0 = getattr(thismodule, "cached_dict")[key] else: df0 = pd.read_sql(key, path) elif backend == "memory": df0 = getattr(thismodule, "cached_dict")[key] else: raise ValueError("no %s option for backend" % backend) df0[date] = pd.to_datetime(df0[date]) # 向前延拓 is_changed = False if df0.iloc[0][date] > start_obj and not fetchonly: kws["start"] = start_str kws["end"] = ( df0.iloc[0][date] - pd.Timedelta(days=1) ).strftime("%Y%m%d") if has_weekday(kws["start"], kws["end"]): # 考虑到海外市场的不同情况,不用 opendate 判断,采取保守型判别 df1 = f(*args, **kws) if df1 is not None and len(df1) > 0: df1 = df1[df1["date"] <= kws["end"]] if df1 is not None and len(df1) > 0: is_changed = True df0 = df1.append(df0, ignore_index=True, sort=False) # 向后延拓 if df0.iloc[-1][date] < end_obj and not fetchonly: nextday_str = ( df0.iloc[-1][date] + dt.timedelta(days=1) ).strftime("%Y%m%d") if len(df0[df0["date"] == df0.iloc[-1]["date"]]) == 1: kws["start"] = (df0.iloc[-1][date]).strftime("%Y%m%d") else: # 单日多行的表默认最后一日是准确的,不再刷新了 kws["start"] = nextday_str kws["end"] = end_str if has_weekday(nextday_str, kws["end"]): # 新更新的日期里有工作日 df2 = f(*args, **kws) if df2 is not None and len(df2) > 0: df2 = df2[df2["date"] >= kws["start"]] if df2 is not None and len(df2) > 0: is_changed = True if ( len(df0[df0["date"] == df0.iloc[-1]["date"]]) == 1 ): df0 = df0.iloc[:-1] df0 = df0.append(df2, ignore_index=True, sort=False) # 注意这里抹去更新了原有最后一天的缓存,这是因为日线最新一天可能有实时数据污染 except (FileNotFoundError, exc.ProgrammingError, KeyError) as e: if fetchonly: logger.error( "no cache in backend for %s but you insist `fetchonly`" % code ) raise e if precached: if start_obj > precached_obj: kws["start"] = precached if end_obj < today_obj(): kws["end"] = ( today_obj() - dt.timedelta(days=1) ).strftime("%Y%m%d") is_changed = True df0 = f(*args, **kws) if df0 is not None and len(df0) > 0 and is_changed: if backend == "csv": df0.to_csv(os.path.join(path, key), index=False) elif backend == "sql": df0.to_sql(key, con=path, if_exists="replace", index=False) # elif backend == "memory": # 总是刷新内存层,即使是硬盘缓存 d = getattr(thismodule, "cached_dict") d[key] = df0 if df0 is not None and len(df0) > 0: df0 = df0[df0["date"] <= end_str] df0 = df0[df0["date"] >= start_str] return df0 return wrapper return cached def fetch_backend(key): prefix = ioconf.get("prefix", "") key = prefix + key backend = ioconf.get("backend") path = ioconf.get("path") if backend == "csv": key = key + ".csv" try: if backend == "csv": df0 = pd.read_csv(os.path.join(path, key)) elif backend == "sql": df0 = pd.read_sql(key, path) else: raise ValueError("no %s option for backend" % backend) return df0 except (FileNotFoundError, exc.ProgrammingError, KeyError): return None def save_backend(key, df, mode="a", header=False): prefix = ioconf.get("prefix", "") key = prefix + key backend = ioconf.get("backend") path = ioconf.get("path") if backend == "csv": key = key + ".csv" if backend == "csv": if mode == "a": df.to_csv(os.path.join(path, key), index=False, header=header, mode=mode) else: df.to_csv(os.path.join(path, key), index=False, mode=mode) elif backend == "sql": if mode == "a": mode = "append" else: mode = "replace" df.to_sql(key, con=path, if_exists=mode, index=False) else: raise ValueError("no %s option for backend" % backend) logger.debug("%s saved into backend successfully" % key) def check_cache(*args, omit_lines=0, **kws): if omit_lines == 0: assert ( _get_daily(*args, wrapper=False, **kws) .reset_index(drop=True) .equals(get_daily(*args, **kws).reset_index(drop=True)) ) else: assert ( _get_daily(*args, wrapper=False, **kws) .reset_index(drop=True)[:-omit_lines] .equals(get_daily(*args, **kws).reset_index(drop=True)[:-omit_lines]) ) @data_source("jq") def _get_index_weight_range(code, start, end): if len(code.split(".")) != 2: code = _inverse_convert_code(code) start_obj = dt.datetime.strptime(start.replace("-", "").replace("/", ""), "%Y%m%d") end_obj = dt.datetime.strptime(end.replace("-", "").replace("/", ""), "%Y%m%d") start_m = start_obj.replace(day=1) if start_m < start_obj: start_m = start_m + relativedelta(months=1) end_m = end_obj.replace(day=1) if end_obj < end_m: end_m = end_m - relativedelta(months=1) d = start_m df = pd.DataFrame({"code": [], "weight": [], "display_name": [], "date": []}) while True: if d > end_m: df["date"] = pd.to_datetime(df["date"]) return df logger.debug("fetch index weight on %s for %s" % (d, code)) df0 = get_index_weights(index_id=code, date=d.strftime("%Y-%m-%d")) df0["code"] = df0.index df = df.append(df0, ignore_index=True, sort=False) d = d + relativedelta(months=1) @data_source("jq") def _get_peb_range(code, start, end): # 盈利,净资产,总市值 """ 获取指定指数一段时间内的 pe pb 值。 :param code: 聚宽形式指数代码。 :param start: :param end: :return: pd.DataFrame """ if len(code.split(".")) != 2: code = _inverse_convert_code(code) data = {"date": [], "pe": [], "pb": []} for d in pd.date_range(start=start, end=end, freq="W-FRI"): data["date"].append(d) logger.debug("compute pe pb on %s" % d) r = get_peb(code, date=d.strftime("%Y-%m-%d")) data["pe"].append(r["pe"]) data["pb"].append(r["pb"]) return pd.DataFrame(data) def get_stock_peb_range(code, start, end, wrapper=False): """ 获取股票历史 pe pb :param code: :param start: :param end: :return: """ if code.startswith("HK") and code[2:].isdigit(): code = code[2:] count = (today_obj() - dt.datetime.strptime(start, "%Y%m%d")).days df = get_historical_fromxq(code, count, full=True) df = df[["date", "pe", "pb", "ps"]] if not wrapper: df = df[df["date"] >= start] df = df[df["date"] <= end] return df @lru_cache() def ttjjcode(code): """ 将天天基金的持仓股票代码或其他来源的代码标准化 :param code: str. :return: str. """ code = code.strip() if code.endswith(".HK"): return "HK" + code[:-3] elif code.endswith(".US"): return code[:-3] elif code.isdigit() and len(code) == 5: return "HK" + code elif code.isdigit() and len(code) == 6: if ( code.startswith("16") or code.startswith("15") or code.startswith("12") or code.startswith("0") or code.startswith("3") ): # 注意这里只能对应个股,指数代码有重叠没有办法的事 return "SZ" + code elif code.startswith("5") or code.startswith("6") or code.startswith("11"): return "SH" + code else: logger.warning("unrecognized code format %s" % code) return "0" else: logger.info("not so sure about code format %s, taken as US stock" % code) return code def get_fund_peb(code, date, threhold=0.3): """ 根据基金的股票持仓,获取对应日期的 pe,pb 估值 :param code: str. 基金代码 :param date: :param threhold: float, default 0.3. 为了计算快速,占比小于千分之三的股票将舍弃 :return: """ if code.startswith("F"): code = code[1:] date = date.replace("/", "").replace("-", "") d = dt.datetime.strptime(date, "%Y%m%d") if d.month > 3 and d.month < 8: year = d.year - 1 season = 4 elif d.month <= 3: year = d.year - 1 season = 2 else: year = d.year season = 2 # season 只选 2,4, 具有更详细的持仓信息 df = get_fund_holdings(code, year, season) if df is None: if season == 4: season = 2 else: year -= 1 season = 4 df = get_fund_holdings(code, year, season) if df is None: logger.warning("%s seems has no holdings data in this time %s" % (code, year)) return {"pe": None, "pb": None} df = df[df["ratio"] >= threhold] df["scode"] = df["code"].apply(ttjjcode) df = df[df["scode"] != "0"] if len(df) == 0: return {"pe": None, "pb": None} pel, pbl = [], [] for i, r in df.iterrows(): try: fdf = get_daily("peb-" + r["scode"], end=date, prev=60) if len(fdf) == 0: # 已退市或改名 logger.warning("%s: 无法获取,可能已退市,当时休市或改名" % r["scode"]) pel.append(None) pbl.append(None) else: fdf = fdf.iloc[-1] pel.append(fdf["pe"]) pbl.append(fdf["pb"]) except (KeyError, TypeError, IndexError) as e: logger.warning( "%s: 获取历史估值出现问题: %s, 可能由于网站故障或股票代码非中美市场" % (r["scode"], e.args[0]) ) pel.append(None) pbl.append(None) df["pe"] = pel df["pb"] = pbl r = {} pedf = df[~pd.isna(df["pe"])] pbdf = df[~pd.isna(df["pb"])] if len(pbdf) < 0.5 * len(df): # 有时候会有个别标的有pb值 r["pb"] = None else: pbdf["b"] = pbdf["ratio"] / (pbdf["pb"] + 0.000001) r["pb"] = pbdf.ratio.sum() / pbdf.b.sum() if len(pedf) == 0: r["pe"] = None else: pedf["e"] = pedf["ratio"] / (pedf["pe"] + 0.000001) r["pe"] = pedf.ratio.sum() / pedf.e.sum() return r def get_fund_peb_range(code, start, end): """ 获取一段时间的基金历史估值,每周五为频率 :param code: :param start: :param end: :return: """ if code.startswith("F"): code = code[1:] data = {"date": [], "pe": [], "pb": []} for d in pd.date_range(start=start, end=end, freq="W-FRI"): data["date"].append(d) r = get_fund_peb(code, date=d.strftime("%Y-%m-%d")) data["pe"].append(r["pe"]) data["pb"].append(r["pb"]) return pd.DataFrame(data) def set_backend(**ioconf): """ 设定 xalpha get_daily 函数的缓存后端,默认为内存。 ioconf 参数设置可参考 :func:`cachedio` :param ioconf: :return: None. """ if not ioconf: ioconf = {"backend": "memory"} get_daily = cachedio(**ioconf)(_get_daily) prefix = ioconf.get("prefix", "") ioconf["prefix"] = "iw-" + prefix get_index_weight_range = cachedio(**ioconf)(_get_index_weight_range) ioconf["prefix"] = "peb-" + prefix get_peb_range = cachedio(**ioconf)(_get_peb_range) setattr(thismodule, "get_daily", get_daily) setattr(xamodule, "get_daily", get_daily) setattr(thismodule, "get_index_weight_range", get_index_weight_range) setattr(thismodule, "get_peb_range", get_peb_range) ioconf["prefix"] = prefix setattr(thismodule, "ioconf", ioconf) set_backend() @data_source("jq") def get_peb(index, date=None, table=False): """ 获取指数在指定日期的 pe 和 pb。采用当时各公司的最新财报和当时的指数成分股权重加权计算。 :param index: str. 聚宽形式的指数代码。 :param date: str. %Y-%m-%d :param table: Optioanl[bool], default False. True 时返回整个计算的 DataFrame,用于 debug。 :return: Dict[str, float]. 包含 pe 和 pb 值的字典。 """ if len(index.split(".")) == 2: index = _convert_code(index) middle = dt.datetime.strptime( date.replace("/", "").replace("-", ""), "%Y%m%d" ).replace(day=1) iwdf = get_index_weight_range( index, start=(middle - dt.timedelta(days=10)).strftime("%Y-%m-%d"), end=(middle + dt.timedelta(days=6)).strftime("%Y-%m-%d"), ) q = query(valuation).filter(valuation.code.in_(list(iwdf.code))) logger.debug("get_fundamentals on %s" % (date)) df = get_fundamentals(q, date=date) df = df.merge(iwdf, on="code") df["e"] = df["weight"] / df["pe_ratio"] df["b"] = df["weight"] / df["pb_ratio"] df["p"] = df["weight"] tote = df.e.sum() totb = df.b.sum() if table: return df return { "pe": (round(100.0 / tote, 3) if tote != 0 else np.inf), "pb": (round(100.0 / totb, 3) if totb != 0 else np.inf), } @data_source("jq") def get_sw_from_jq(code, start=None, end=None, **kws): """ :param code: str. eg. 801180 申万行业指数 :param start: :param end: :param kws: :return: """ logger.debug("get sw data of %s" % code) df = finance.run_query( query(finance.SW1_DAILY_VALUATION) .filter(finance.SW1_DAILY_VALUATION.date >= start) .filter(finance.SW1_DAILY_VALUATION.date <= end) .filter(finance.SW1_DAILY_VALUATION.code == code) .order_by(finance.SW1_DAILY_VALUATION.date.asc()) ) df["date"] = pd.to_datetime(df["date"]) return df @data_source("jq") def get_teb(code, date): if len(code.split(".")) != 2: code = _inverse_convert_code(code) sl = get_index_stocks(code, date=date) logger.debug("get fundamentals from jq for %s" % code) df = get_fundamentals(query(valuation).filter(valuation.code.in_(sl)), date=date) df["e"] = df["market_cap"] / df["pe_ratio"] df["b"] = df["market_cap"] / df["pb_ratio"] return {"e": df["e"].sum(), "b": df["b"].sum(), "m": df["market_cap"].sum()} # 亿人民币 def get_teb_range(code, start, end, freq="W-FRI"): if len(code.split(".")) != 2: code = _inverse_convert_code(code) data = {"date": [], "e": [], "b": [], "m": []} for d in pd.date_range(start, end, freq=freq): data["date"].append(d) r = get_teb(code, d.strftime("%Y-%m-%d")) data["e"].append(r["e"]) data["b"].append(r["b"]) data["m"].append(r["m"]) df = pd.DataFrame(data) return df def _convert_code(code): """ 将聚宽形式的代码转化为 xalpha 形式 :param code: :return: """ no, mk = code.split(".") if mk == "XSHG": return "SH" + no elif mk == "XSHE": return "SZ" + no def _inverse_convert_code(code): """ 将 xalpha 形式的代码转化为聚宽形式 :param code: :return: """ if code.startswith("SH"): return code[2:] + ".XSHG" elif code.startswith("SZ"): return code[2:] + ".XSHE" @lru_cache_time(ttl=60, maxsize=512) def get_bar( code, prev=24, interval=3600, _from=None, handler=True, start=None, end=None ): """ :param code: str. 支持雪球和英为的代码 :param prev: points of data from now to back, often limited by API around several hundreds :param interval: float, seconds. need to match the corresponding API, typical values include 60, 300, 3600, 86400, 86400*7 :param handler: bool. Default True. 若为 False,则 handler 钩子失效,用于钩子函数中的嵌套。 :return: pd.DataFrame """ if handler: if getattr(thismodule, "get_bar_handler", None): args = inspect.getargvalues(inspect.currentframe()) f = getattr(thismodule, "get_bar_handler") fr = f(**args.locals) if fr is not None: return fr if not _from: if ( (start is not None) and (end is not None) and (code.startswith("SH") or code.startswith("SZ")) ): _from = "jq" elif code.startswith("SH") or code.startswith("SZ"): _from = "xueqiu" elif code.isdigit(): _from = "cninvesting" elif code.startswith("HK") and code[2:7].isdigit(): _from = "xueqiu" code = code[2:] elif len(code.split("-")) >= 2 and len(code.split("-")[0]) <= 3: _from = code.split("-")[0] code = "-".join(code.split("-")[1:]) elif len(code.split("/")) > 1: _from = "cninvesting" code = get_investing_id(code) else: _from = "xueqiu" # 美股 if _from in ["xq", "xueqiu", "XQ"]: return get_bar_fromxq(code, prev, interval) elif _from in ["IN", "cninvesting", "investing"]: return get_bar_frominvesting(code, prev, interval) elif _from in ["INA"]: return get_bar_frominvesting(code, prev, interval) # 这里 investing app 源是 404,只能用网页源 elif _from in ["jq"]: code, type_ = decouple_code(code) # 关于复权,聚宽各个时间密度的数据都有复权,雪球源日线以上的高频数据没有复权 type_map = {"after": "post", "before": "pre", "normal": None} return get_bar_fromjq( code, start=start, end=end, interval=interval, fq=type_map[type_] ) elif _from in ["wsj"]: return get_bar_fromwsj(code, interval=interval)[-prev:] else: raise ParserFailure("unrecoginized _from %s" % _from) @data_source("jq") def get_bar_fromjq(code, start, end, interval, fq="pre"): code = _inverse_convert_code(code) trans = { "60": "1m", "120": "2m", "300": "5m", "900": "15m", "1800": "30m", "3600": "60m", "7200": "120m", "86400": "daily", } interval = trans.get(str(interval), interval) logger.debug("calling ``get_price`` from jq with %s" % code) return get_price(code, start_date=start, end_date=end, frequency=interval, fq=fq) def get_bar_frominvesting(code, prev=120, interval=3600): """ get bar data beyond daily bar :param code: str. investing id or url :param prev: int, data points from now, max might be around 500, if exceed, only None is returnd :param interval: default 3600. optional 60, 300, 900, 1800, 18000, 86400, "week", "month" :return: pd.DataFrame or None if prev and interval unmatch the API """ if interval == "day": interval = 86400 elif interval == "hour": interval = 3600 elif interval == "minute": interval = 60 elif interval == 86400 * 7: interval = "week" elif interval == 86400 * 30: interval = "month" if len(code.split("/")) == 2: code = get_investing_id(code) url = "https://cn.investing.com" headers = { "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)\ AppleWebKit/537.36 (KHTML, like Gecko)", "Host": "cn.investing.com", "Referer": "https://cn.investing.com/commodities/", "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-origin", "X-Requested-With": "XMLHttpRequest", } r = rget( url + "/common/modules/js_instrument_chart/api/data.php?pair_id={code}&pair_id_for_news={code}\ &chart_type=area&pair_interval={interval}&candle_count={prev}&events=yes&volume_series=yes&period=".format( code=code, prev=str(prev), interval=str(interval) ), headers=headers, ) if not r.text: return # None r = r.json() df = pd.DataFrame(r["candles"], columns=["date", "close", "0", "1"]) df = df.drop(["0", "1"], axis=1) df["date"] = df["date"].apply( lambda t: dt.datetime.fromtimestamp(t / 1000, tz=tz_bj).replace(tzinfo=None) ) return df def get_bar_fromxq(code, prev, interval=3600): """ :param code: :param prev: :param interval: 1m, 5m, 15m, 30m, 60m, 120m, month, quarter, year, week, day :return: """ # max interval is also around 500 trans = { "60": "1m", "300": "5m", "900": "15m", "1800": "30m", "3600": "60m", "7200": "120m", "86400": "day", "604800": "week", "2592000": "month", } code, type_ = decouple_code(code) interval = trans.get(str(interval), interval) url = "https://stock.xueqiu.com/v5/stock/chart/kline.json?symbol={code}&begin={tomorrow}&period={interval}&type={type_}\ &count=-{prev}&indicator=kline,pe,pb,ps,pcf,market_capital,agt,ggt,balance".format( code=code, tomorrow=int(tomorrow_ts() * 1000), prev=prev, interval=interval, type_=type_, ) r = rget( url, headers={"user-agent": "Mozilla/5.0"}, cookies={"xq_a_token": get_token()} ) if not r.text: return # None else: df = pd.DataFrame(r.json()["data"]["item"], columns=r.json()["data"]["column"]) df["date"] = df["timestamp"].apply( lambda t: dt.datetime.fromtimestamp(t / 1000, tz=tz_bj).replace(tzinfo=None) ) df = df[ [ "date", "open", "high", "low", "close", "volume", "turnoverrate", "percent", ] ] return df def get_bar_fromwsj(code, token=None, interval=3600): # proxy required # code = "FUTURE/US/XNYM/CLM20" # TODO: also not explore the code format here extensively trans = {"3600": "1H"} # TODO: there is other freq tags, but I have no time to explore them, contributions are welcome:) freq = trans.get(str(interval), interval) if not token: token = "cecc4267a0194af89ca343805a3e57af" # the thing I am concerned here is whether token is refreshed params = { "json": '{"Step":"PT%s","TimeFrame":"D5","EntitlementToken":"%s",\ "IncludeMockTick":true,"FilterNullSlots":false,"FilterClosedPoints":true,"IncludeClosedSlots":false,\ "IncludeOfficialClose":true,"InjectOpen":false,"ShowPreMarket":false,"ShowAfterHours":false,\ "UseExtendedTimeFrame":false,"WantPriorClose":true,"IncludeCurrentQuotes":false,\ "ResetTodaysAfterHoursPercentChange":false,\ "Series":[{"Key":"%s","Dialect":"Charting","Kind":"Ticker","SeriesId":"s1","DataTypes":["Last"]}]}' % (freq, token, code), "ckey": token[:10], } r = rget_json( "https://api-secure.wsj.net/api/michelangelo/timeseries/history", params=params, headers={ "user-agent": "Mozilla/5.0", "Accept": "application/json, text/javascript, */*; q=0.01", "Dylan2010.EntitlementToken": token, "Host": "api-secure.wsj.net", "Origin": "https://www.marketwatch.com", "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "cross-site", }, ) df = pd.DataFrame( { "date": r["TimeInfo"]["Ticks"], "close": [n[0] for n in r["Series"][0]["DataPoints"]], } ) df["date"] = pd.to_datetime(df["date"] * 1000000) + pd.Timedelta(hours=8) df = df[df["close"] > -100.0] # 存在未来数据占位符需要排除 return df class vinfo(basicinfo, indicator): """ vinfo is an info like class wrapper for get_daily, it behaves like info """ def __init__( self, code, name=None, start=None, end=None, rate=0, col="close", normalization=True, **kws ): if not name: try: name = get_rt(code)["name"] except: name = code self.name = name self.code = code self.start = start # None is one year ago self.end = end # None is yesterday df = get_daily(code, start=start, end=end) df[col] = pd.to_numeric(df[col]) # in case the col is not float df["totvalue"] = df[col] if normalization: df["netvalue"] = df[col] / df.iloc[0][col] else: df["netvalue"] = df[col] self.price = df self.round_label = kws.get("round_label", 0) self.dividend_label = kws.get("dividend_label", 0) self.value_label = kws.get("value_label", 1) # 默认按金额赎回 self.specialdate = [] self.fenhongdate = [] self.zhesuandate = [] self.rate = rate VInfo = vinfo
33.522752
277
0.544876
import os import sys import time import datetime as dt import numpy as np import pandas as pd import logging import inspect from bs4 import BeautifulSoup from functools import wraps, lru_cache from uuid import uuid4 from sqlalchemy import exc from dateutil.relativedelta import relativedelta try: from jqdatasdk import ( get_index_weights, query, get_fundamentals, valuation, get_query_count, finance, get_index_stocks, macro, get_price, ) except ImportError: try: from jqdata import finance, macro except ImportError: pass from xalpha.info import basicinfo, fundinfo, mfundinfo, get_fund_holdings from xalpha.indicator import indicator from xalpha.cons import ( rget, rpost, rget_json, rpost_json, tz_bj, last_onday, region_trans, today_obj, _float, ) from xalpha.provider import data_source from xalpha.exceptions import DataPossiblyWrong, ParserFailure pd.options.mode.chained_assignment = None thismodule = sys.modules[__name__] xamodule = sys.modules["xalpha"] logger = logging.getLogger(__name__) def tomorrow_ts(): dto = dt.datetime.now() + dt.timedelta(1) return dto.timestamp() def has_weekday(start, end): for d in pd.date_range(start, end): if d.weekday() < 5: return True return False def ts2pdts(ts): dto = dt.datetime.fromtimestamp(ts / 1000, tz=tz_bj).replace(tzinfo=None) return dto.replace( hour=0, minute=0, second=0, microsecond=0 ) def decouple_code(code): if len(code[1:].split(".")) > 1: type_ = code.split(".")[-1] code = ".".join(code.split(".")[:-1]) if type_.startswith("b") or type_.startswith("B"): type_ = "before" elif type_.startswith("a") or type_.startswith("A"): type_ = "after" elif type_.startswith("n") or type_.startswith("N"): type_ = "normal" else: logger.warning( "unrecoginzed flag for adjusted factor %s, use default" % type_ ) type_ = "before" else: type_ = "before" return code, type_ def lru_cache_time(ttl=None, maxsize=None): def wrapper(func): @lru_cache(maxsize) def time_aware(_ttl, *args, **kwargs): return func(*args, **kwargs) setattr(thismodule, func.__name__ + "_ttl", time_aware) @wraps(func) def newfunc(*args, **kwargs): ttl_hash = round(time.time() / ttl) f_ttl = getattr(thismodule, func.__name__ + "_ttl") return f_ttl(ttl_hash, *args, **kwargs) return newfunc return wrapper @lru_cache_time(ttl=300) def get_token(): r = rget("https://xueqiu.com", headers={"user-agent": "Mozilla"}) return r.cookies["xq_a_token"] def get_historical_fromxq(code, count, type_="before", full=False): url = "https://stock.xueqiu.com/v5/stock/chart/kline.json?symbol={code}&begin={tomorrow}&period=day&type={type_}&count=-{count}" if full: url += "&indicator=kline,pe,pb,ps,pcf,market_capital,agt,ggt,balance" r = rget_json( url.format( code=code, tomorrow=int(tomorrow_ts() * 1000), count=count, type_=type_ ), cookies={"xq_a_token": get_token()}, headers={"user-agent": "Mozilla/5.0"}, ) df = pd.DataFrame(data=r["data"]["item"], columns=r["data"]["column"]) df["date"] = (df["timestamp"]).apply(ts2pdts) return df @lru_cache() def get_industry_fromxq(code): url = ( "https://xueqiu.com/stock/industry/stockList.json?code=%s&type=1&size=100" % code ) r = rget_json(url, cookies={"xq_a_token": get_token()}) return r def get_historical_fromcninvesting(curr_id, st_date, end_date, app=False): data = { "curr_id": curr_id, "interval_sec": "Daily", "sort_col": "date", "sort_ord": "DESC", "action": "historical_data", } if not app: # fetch from web api r = rpost( "https://cn.investing.com/instruments/HistoricalDataAjax", data=data, headers={ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)\ AppleWebKit/537.36 (KHTML, like Gecko)", "Host": "cn.investing.com", "X-Requested-With": "XMLHttpRequest", }, ) else: # fetch from app api r = rpost( "https://cnappapi.investing.com/instruments/HistoricalDataAjax", data=data, headers={ "Accept": "*/*", "Accept-Encoding": "gzip", "Accept-Language": "zh-cn", "Cache-Control": "no-cache", "Connection": "keep-alive", "User-Agent": "Investing.China/0.0.3 CFNetwork/1121.2.2 Darwin/19.3.0", "ccode": "CN", #'ccode_time': '1585551041.986028', "x-app-ver": "117", "x-meta-ver": "14", "x-os": "ios", "x-uuid": str(uuid4()), "Host": "cn.investing.com", "X-Requested-With": "XMLHttpRequest", }, ) s = BeautifulSoup(r.text, "lxml") dfdict = {} cols = [] for col in s.find_all("th"): dfdict[str(col.contents[0])] = [] cols.append(str(col.contents[0])) num_cols = len(cols) for i, td in enumerate(s.find_all("td")[:-5]): if cols[i % num_cols] == "日期": dfdict[cols[i % num_cols]].append( dt.datetime.strptime(str(td.string), "%Y年%m月%d日") ) else: dfdict[cols[i % num_cols]].append(str(td.string)) return pd.DataFrame(dfdict) def prettify(df): _map = { "日期": "date", "收盘": "close", "开盘": "open", "高": "high", "低": "low", "涨跌幅": "percent", "交易量": "volume", } df.rename(_map, axis=1, inplace=True) if len(df) > 1 and df.iloc[1]["date"] < df.iloc[0]["date"]: df = df[::-1] # df = df[["date", "open", "close", "high", "low", "percent"]] df1 = df[["date"]] for k in ["open", "close", "high", "low", "volume"]: if k in df.columns: df1[k] = df[k].apply(_float) df1["percent"] = df["percent"] return df1 def dstr2dobj(dstr): if len(dstr.split("/")) > 1: d_obj = dt.datetime.strptime(dstr, "%Y/%m/%d") elif len(dstr.split(".")) > 1: d_obj = dt.datetime.strptime(dstr, "%Y.%m.%d") elif len(dstr.split("-")) > 1: d_obj = dt.datetime.strptime(dstr, "%Y-%m-%d") else: d_obj = dt.datetime.strptime(dstr, "%Y%m%d") return d_obj @lru_cache(maxsize=1024) def get_investing_id(suburl, app=False): if not app: url = "https://cn.investing.com" else: url = "https://cnappapi.investing.com" if not suburl.startswith("/"): url += "/" url += suburl if not app: headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36" } else: headers = { "Accept": "*/*", "Accept-Encoding": "gzip", "Accept-Language": "zh-cn", "Cache-Control": "no-cache", "Connection": "keep-alive", "User-Agent": "Investing.China/0.0.3 CFNetwork/1121.2.2 Darwin/19.3.0", "ccode": "CN", #'ccode_time': '1585551041.986028', "x-app-ver": "117", "x-meta-ver": "14", "x-os": "ios", "x-uuid": str(uuid4()), "Host": "cn.investing.com", "X-Requested-With": "XMLHttpRequest", } r = rget( url, headers=headers, ) s = BeautifulSoup(r.text, "lxml") pid = s.find("span", id="last_last")["class"][-1].split("-")[1] return pid def _variate_ua(): last = 20 + np.random.randint(20) ua = [] ua.append( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko)" ) ua.append( "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1" ) choice = np.random.randint(2) return ua[choice][:last] @lru_cache_time(ttl=120, maxsize=128) def get_rmb(start=None, end=None, prev=360, currency="USD/CNY"): bl = ["USD", "EUR", "100JPY", "HKD", "GBP", "AUD", "NZD", "SGD", "CHF", "CAD"] al = [ "MYR", "RUB", "ZAR", "KRW", "AED", "SAR", "HUF", "PLN", "DKK", "SEK", "NOK", "TRY", "MXN", "THB", ] is_inverse = False if (currency[:3] in al) or (currency[4:] in bl): is_inverse = True currency = currency[4:] + "/" + currency[:3] url = "http://www.chinamoney.com.cn/ags/ms/cm-u-bk-ccpr/CcprHisNew?startDate={start_str}&endDate={end_str}&currency={currency}&pageNum=1&pageSize=300" if not end: end_obj = today_obj() else: end_obj = dstr2dobj(end) if not start: start_obj = end_obj - dt.timedelta(prev) else: start_obj = dstr2dobj(start) start_str = start_obj.strftime("%Y-%m-%d") end_str = end_obj.strftime("%Y-%m-%d") count = (end_obj - start_obj).days + 1 rl = [] # API 很奇怪,需要经常变 UA 才好用 headers = { "Referer": "http://www.chinamoney.com.cn/chinese/bkccpr/", "Origin": "http://www.chinamoney.com.cn", "Host": "www.chinamoney.com.cn", "X-Requested-With": "XMLHttpRequest", } if count <= 360: headers.update({"user-agent": _variate_ua()}) r = rpost_json( url.format(start_str=start_str, end_str=end_str, currency=currency), headers=headers, ) rl.extend(r["records"]) else: # data more than 1 year cannot be fetched once due to API limitation sepo_obj = end_obj sepn_obj = sepo_obj - dt.timedelta(360) # sep0_obj = end_obj - dt.timedelta(361) while sepn_obj > start_obj: # [sepn sepo] headers.update({"user-agent": _variate_ua()}) r = rpost_json( url.format( start_str=sepn_obj.strftime("%Y-%m-%d"), end_str=sepo_obj.strftime("%Y-%m-%d"), currency=currency, ), headers=headers, ) rl.extend(r["records"]) sepo_obj = sepn_obj - dt.timedelta(1) sepn_obj = sepo_obj - dt.timedelta(360) headers.update({"user-agent": _variate_ua()}) r = rpost_json( url.format( start_str=start_obj.strftime("%Y-%m-%d"), end_str=sepo_obj.strftime("%Y-%m-%d"), currency=currency, ), headers=headers, ) rl.extend(r["records"]) data = {"date": [], "close": []} for d in rl: data["date"].append(pd.Timestamp(d["date"])) data["close"].append(d["values"][0]) df = pd.DataFrame(data) df = df[::-1] df["close"] = pd.to_numeric(df["close"]) if is_inverse: df["close"] = 1 / df["close"] return df def get_fund(code): # 随意设置非空 path,防止嵌套缓存到 fundinfo if code[0] == "F": if code.startswith("F96"): return get_historical_from_ttjj_oversea(code) else: df = fundinfo(code[1:], path="nobackend", priceonly=True).price elif code[0] == "T": df = fundinfo(code[1:], path="nobackend", priceonly=True).price df["netvalue"] = df["totvalue"] elif code[0] == "M": df = mfundinfo(code[1:], path="nobackend").price else: raise ParserFailure("Unknown fund code %s" % code) df["close"] = df["netvalue"] return df[["date", "close"]] def get_historical_from_ttjj_oversea(code, start=None, end=None): if code.startswith("F"): code = code[1:] pagesize = ( dt.datetime.strptime(end, "%Y%m%d") - dt.datetime.strptime(start, "%Y%m%d") ).days + 1 r = rget_json( "http://overseas.1234567.com.cn/overseasapi/OpenApiHander.ashx?api=HKFDApi&m=MethodJZ&hkfcode={hkfcode}&action=2&pageindex=0&pagesize={pagesize}&date1={startdash}&date2={enddash}&callback=".format( hkfcode=get_hkfcode(code), pagesize=pagesize, startdash=start[:4] + "-" + start[4:6] + "-" + start[6:], enddash=end[:4] + "-" + end[4:6] + "-" + end[6:], ) ) datalist = {"date": [], "close": []} for dd in r["Data"]: datalist["date"].append(pd.to_datetime(dd["PDATE"])) datalist["close"].append(dd["NAV"]) df = pd.DataFrame(datalist) df = df[df["date"] <= end] df = df[df["date"] >= start] df = df.sort_values("date", ascending=True) return df def get_portfolio_fromttjj(code, start=None, end=None): startobj = dt.datetime.strptime(start, "%Y%m%d") endobj = dt.datetime.strptime(end, "%Y%m%d") if (endobj - startobj).days < 90: return None # note start is always 1.1 4.1 7.1 10.1 in incremental updates if code.startswith("F"): code = code[1:] r = rget("http://fundf10.eastmoney.com/zcpz_{code}.html".format(code=code)) s = BeautifulSoup(r.text, "lxml") table = s.find("table", class_="tzxq") df = pd.read_html(str(table))[0] df["date"] = pd.to_datetime(df["报告期"]) df["stock_ratio"] = df["股票占净比"].replace("---", "0%").apply(lambda s: _float(s[:-1])) df["bond_ratio"] = df["债券占净比"].replace("---", "0%").apply(lambda s: _float(s[:-1])) df["cash_ratio"] = df["现金占净比"].replace("---", "0%").apply(lambda s: _float(s[:-1])) # df["dr_ratio"] = df["存托凭证占净比"].replace("---", "0%").apply(lambda s: xa.cons._float(s[:-1])) df["assets"] = df["净资产(亿元)"] df = df[::-1] return df[["date", "stock_ratio", "bond_ratio", "cash_ratio", "assets"]] # this is the most elegant approach to dispatch get_daily, the definition can be such simple # you actually don't need to bother on start end blah, everything is taken care of by ``cahcedio`` @data_source("jq") def get_fundshare_byjq(code, **kws): code = _inverse_convert_code(code) df = finance.run_query( query(finance.FUND_SHARE_DAILY) .filter(finance.FUND_SHARE_DAILY.code == code) .filter(finance.FUND_SHARE_DAILY.date >= kws["start"]) .filter(finance.FUND_SHARE_DAILY.date <= kws["end"]) .order_by(finance.FUND_SHARE_DAILY.date) ) df["date"] = pd.to_datetime(df["date"]) df = df[["date", "shares"]] return df @lru_cache(maxsize=1024) def get_futu_id(code): r = rget("https://www.futunn.com/stock/{code}".format(code=code)) sind = r.text.find("securityId") futuid = r.text[sind : sind + 30].split("=")[1].split(";")[0].strip(" ").strip("'") sind = r.text.find("marketType") market = r.text[sind : sind + 30].split("=")[1].split(";")[0].strip().strip("''") return futuid, market def get_futu_historical(code, start=None, end=None): fid, market = get_futu_id(code) r = rget( "https://www.futunn.com/new-quote/kline?security_id={fid}&type=2&market_type={market}".format( fid=fid, market=market ) ) df = pd.DataFrame(r.json()["data"]["list"]) df["date"] = df["k"].map( lambda s: dt.datetime.fromtimestamp(s) .replace(hour=0, minute=0, second=0, microsecond=0) .replace(tzinfo=None) ) df["open"] = df["o"] / 1000 df["close"] = df["c"] / 1000 df["high"] = df["h"] / 1000 df["low"] = df["l"] / 1000 df["volume"] = df["v"] df = df.drop(["k", "t", "o", "c", "h", "l", "v"], axis=1) return df def get_historical_fromsp(code, start=None, end=None, region="us", **kws): if code.startswith("SP"): code = code[2:] if len(code.split(".")) > 1: col = code.split(".")[1] code = code.split(".")[0] else: col = "1" start_obj = dt.datetime.strptime(start, "%Y%m%d") fromnow = (today_obj() - start_obj).days if fromnow < 300: flag = "one" elif fromnow < 1000: flag = "three" else: flag = "ten" url = "https://{region}.spindices.com/idsexport/file.xls?\ selectedModule=PerformanceGraphView&selectedSubModule=Graph\ &yearFlag={flag}YearFlag&indexId={code}".format( region=region, flag=flag, code=code ) r = rget( url, headers={ "sec-fetch-dest": "document", "sec-fetch-mode": "navigate", "sec-fetch-site": "same-origin", "sec-fetch-user": "?1", "upgrade-insecure-requests": "1", }, ) df = pd.read_excel(r.content, engine="xlrd") # print(df.iloc[:10]) df = df.iloc[6:] df = df.dropna() df["close"] = df["Unnamed: " + col] df["date"] = pd.to_datetime(df["Unnamed: 0"]) df = df[["date", "close"]] return df def get_historical_frombb(code, start=None, end=None, **kws): if code.startswith("BB-"): code = code[3:] # end_obj = dt.datetime.strptime(end, "%Y%m%d") start_obj = dt.datetime.strptime(start, "%Y%m%d") fromnow = (today_obj() - start_obj).days if fromnow < 20: years = "1_MONTH" elif fromnow < 300: years = "1_YEAR" else: years = "5_YEAR" url = "https://www.bloomberg.com/markets2/api/history/{code}/PX_LAST?\ timeframe={years}&period=daily&volumePeriod=daily".format( years=years, code=code ) r = rget_json( url, headers={ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko)", "referer": "https://www.bloomberg.com/quote/{code}".format(code=code), "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "same-origin", "accept": "*/*", }, ) df = pd.DataFrame(r[0]["price"]) df["close"] = df["value"] df["date"] = pd.to_datetime(df["dateTime"]) df = df[["date", "close"]] return df def get_historical_fromft(code, start, end, _type="indices"): if not code.isdigit(): code = get_ft_id(code, _type=_type) start = start.replace("/", "").replace("-", "") end = end.replace("/", "").replace("-", "") start = start[:4] + "/" + start[4:6] + "/" + start[6:] end = end[:4] + "/" + end[4:6] + "/" + end[6:] url = "https://markets.ft.com/data/equities/ajax/\ get-historical-prices?startDate={start}&endDate={end}&symbol={code}".format( code=code, start=start, end=end ) r = rget_json(url, headers={"user-agent": "Mozilla/5.0"}) b = BeautifulSoup(r["html"], "lxml") data = {"date": [], "open": [], "close": [], "high": [], "low": []} for i, td in enumerate(b.findAll("td")): if i % 6 == 0: s = td.find("span").string.split(",")[1:] s = ",".join(s) data["date"].append(dt.datetime.strptime(s, " %B %d, %Y")) elif i % 6 == 1: data["open"].append(_float(td.string)) elif i % 6 == 2: data["high"].append(_float(td.string)) elif i % 6 == 3: data["low"].append(_float(td.string)) elif i % 6 == 4: data["close"].append(_float(td.string)) df = pd.DataFrame(data) df = df.iloc[::-1] return df def get_historical_fromyh(code, start=None, end=None): if code.startswith("YH-"): code = code[3:] start_obj = dt.datetime.strptime(start, "%Y%m%d") fromnow = (today_obj() - start_obj).days if fromnow < 20: range_ = "1mo" elif fromnow < 50: range_ = "3mo" elif fromnow < 150: range_ = "6mo" elif fromnow < 300: range_ = "1y" elif fromnow < 600: range_ = "2y" elif fromnow < 1500: range_ = "5y" else: range_ = "10y" url = "https://query1.finance.yahoo.com/v8\ /finance/chart/{code}?region=US&lang=en-US&includePrePost=false\ &interval=1d&range={range_}&corsDomain=finance.yahoo.com&.tsrc=finance".format( code=code, range_=range_ ) # 该 API 似乎也支持起止时间选择参数,period1=1427500800&period2=1585353600 # 也可直接从历史数据页面爬取: https://finance.yahoo.com/quote/CSGOLD.SW/history?period1=1427500800&period2=1585353600&interval=1d&filter=history&frequency=1d r = rget_json(url) data = {} datel = [] for t in r["chart"]["result"][0]["timestamp"]: t = dt.datetime.fromtimestamp(t) if t.second != 0: t -= dt.timedelta(hours=8) datel.append(t.replace(tzinfo=None, hour=0, minute=0, second=0, microsecond=0)) data["date"] = datel for k in ["close", "open", "high", "low"]: data[k] = r["chart"]["result"][0]["indicators"]["quote"][0][k] df = pd.DataFrame(data) return df def get_historical_fromzzindex(code, start, end=None): if code.startswith("ZZ"): code = code[2:] start_obj = dt.datetime.strptime(start, "%Y%m%d") fromnow = (today_obj() - start_obj).days if fromnow < 20: flag = "1%E4%B8%AA%E6%9C%88" elif fromnow < 60: flag = "3%E4%B8%AA%E6%9C%88" # 个月 elif fromnow < 200: flag = "1%E5%B9%B4" # 年 else: flag = "5%E5%B9%B4" r = rget_json( "http://www.csindex.com.cn/zh-CN/indices/index-detail/\ {code}?earnings_performance={flag}&data_type=json".format( code=code, flag=flag ), headers={ "Host": "www.csindex.com.cn", "Referer": "http://www.csindex.com.cn/zh-CN/indices/index-detail/{code}".format( code=code ), "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36", "X-Requested-With": "XMLHttpRequest", "Accept": "application/json, text/javascript, */*; q=0.01", }, ) df = pd.DataFrame(r) df["date"] = pd.to_datetime(df["tradedate"]) df["close"] = df["tclose"].apply(_float) return df[["date", "close"]] def get_historical_fromgzindex(code, start, end): if code.startswith("GZ"): code = code[2:] start = start[:4] + "-" + start[4:6] + "-" + start[6:] end = end[:4] + "-" + end[4:6] + "-" + end[6:] params = { "indexCode": code, "startDate": start, "endDate": end, "frequency": "Day", } r = rget_json( "http://hq.cnindex.com.cn/market/market/getIndexDailyDataWithDataFormat", params=params, ) df = pd.DataFrame(r["data"]["data"], columns=r["data"]["item"]) df["date"] = pd.to_datetime(df["timestamp"]) df = df[["date", "close", "open", "low", "high", "percent", "amount", "volume"]] # TODO: 是否有这些列不全的国证指数? df = df[::-1] return df def get_historical_fromhzindex(code, start, end): if code.startswith("HZ"): code = code[2:] r = rget_json( "http://www.chindices.com/index/values.val?code={code}".format(code=code) ) df = pd.DataFrame(r["data"]) df["date"] = pd.to_datetime(df["date"]) df = df[["date", "price", "pctChange"]] df.rename(columns={"price": "close", "pctChange": "percent"}, inplace=True) df = df[::-1] return df def get_historical_fromesunny(code, start=None, end=None): # code if code.startswith("ESCI"): code = code[4:] + ".ESCI" r = rget( "http://www.esunny.com.cn/chartES/csv/shareday/day_易盛指数_{code}.es".format( code=code ) ) data = [] for l in r.text.split("\n"): row = [s.strip() for s in l.split("|")] # 开 高 低 收 结 if len(row) > 1: data.append(row[:7]) df = pd.DataFrame( data, columns=["date", "open", "high", "low", "close", "settlement", "amount"] ) df["date"] = pd.to_datetime(df["date"]) for c in ["open", "high", "low", "close", "settlement", "amount"]: df[c] = df[c].apply(_float) return df def get_historical_fromycharts(code, start, end, category, metric): params = { "securities": "include:true,id:{code},,".format(code=code), "calcs": "include:true,id:{metric},,".format(metric=metric), "startDate": start, # %m/%d/%Y "endDate": end, # %m/%d/%Y "zoom": "custom", } r = rget_json( "https://ycharts.com/charts/fund_data.json", params=params, headers={ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)\ AppleWebKit/537.36 (KHTML, like Gecko)", "Host": "ycharts.com", "X-Requested-With": "XMLHttpRequest", "Referer": "https://ycharts.com/{category}/{code}/chart/".format( category=category, code=code ), "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-origin", }, ) df = pd.DataFrame( data=r["chart_data"][0][0]["raw_data"], columns=["timestamp", "close"] ) df["date"] = (df["timestamp"]).apply(ts2pdts) return df[["date", "close"]] @lru_cache() def get_bond_rates(rating, date=None): rating = rating.strip() rating_uid = { "N": "2c9081e50a2f9606010a3068cae70001", # 国债 "AAA": "2c9081e50a2f9606010a309f4af50111", "AAA-": "8a8b2ca045e879bf014607ebef677f8e", "AA+": "2c908188138b62cd01139a2ee6b51e25", "AA": "2c90818812b319130112c279222836c3", "AA-": "8a8b2ca045e879bf014607f9982c7fc0", "A+": "2c9081e91b55cc84011be40946ca0925", "A": "2c9081e91e6a3313011e6d438a58000d", "A-": "8a8b2ca04142df6a014148ca880f3046", "A": "2c9081e91e6a3313011e6d438a58000d", "BBB+": "2c9081e91ea160e5011eab1f116c1a59", "BBB": "8a8b2ca0455847ac0145650780ad68fb", "BB": "8a8b2ca0455847ac0145650ba23b68ff", "B": "8a8b2ca0455847ac0145650c3d726901", } # 上边字典不全,非常欢迎贡献 :) def _fetch(date): r = rpost( "https://yield.chinabond.com.cn/cbweb-mn/yc/searchYc?\ xyzSelect=txy&&workTimes={date}&&dxbj=0&&qxll=0,&&yqqxN=N&&yqqxK=K&&\ ycDefIds={uid}&&wrjxCBFlag=0&&locale=zh_CN".format( uid=rating_uid.get(rating, rating), date=date ), ) return r if not date: date = dt.datetime.today().strftime("%Y-%m-%d") r = _fetch(date) while len(r.text.strip()) < 20: # 当天没有数据,非交易日 date = last_onday(date).strftime("%Y-%m-%d") r = _fetch(date) l = r.json()[0]["seriesData"] l = [t for t in l if t[1]] df = pd.DataFrame(l, columns=["year", "rate"]) return df def get_bond_rates_range(rating, duration=3, freq="W-FRI", start=None, end=None): l = [] if rating.startswith("B-"): rating = rating[2:] rs = rating.split(".") if len(rs) > 1: duration = float(rs[1]) rating = rs[0] for d in pd.date_range(start, end, freq=freq): df = get_bond_rates(rating, d.strftime("%Y-%m-%d")) l.append([d, df[df["year"] <= duration].iloc[-1]["rate"]]) return pd.DataFrame(l, columns=["date", "close"]) @data_source("jq") def get_macro(table, start, end, datecol="stat_year"): df = macro.run_query( query(getattr(macro, table)) .filter(getattr(getattr(macro, table), datecol) >= start) .filter(getattr(getattr(macro, table), datecol) <= end) .order_by(getattr(getattr(macro, table), datecol)) ) df[datecol] = pd.to_datetime(df[datecol]) df["date"] = df[datecol] return df def set_handler(method="daily", f=None): setattr(thismodule, "get_" + method + "_handler", f) def _get_daily( code, start=None, end=None, prev=365, _from=None, wrapper=True, handler=True, **kws ): if handler: if getattr(thismodule, "get_daily_handler", None): args = inspect.getargvalues(inspect.currentframe()) f = getattr(thismodule, "get_daily_handler") fr = f(**args.locals) if fr is not None: return fr if not end: end_obj = today_obj() else: end_obj = dstr2dobj(end) if not start: start_obj = end_obj - dt.timedelta(days=prev) else: start_obj = dstr2dobj(start) if not _from: if (code.startswith("SH") or code.startswith("SZ")) and code[2:8].isdigit(): _from = "xueqiu" elif code.endswith("/CNY") or code.startswith("CNY/"): _from = "zjj" elif code.isdigit(): _from = "cninvesting" elif code[0] in ["F", "M", "T"] and code[1:].isdigit(): _from = "ttjj" elif code.startswith("HK") and code[2:7].isdigit(): _from = "xueqiu" code = code[2:] elif code.startswith("SP") and code[2:].split(".")[0].isdigit(): _from = "SP" elif code.startswith("SPC") and code[3:].split(".")[0].isdigit(): _from = "SPC" elif code.startswith("ZZ") and code[4:].isdigit(): # 注意中证系列指数的代码里可能包含字母! _from = "ZZ" elif code.startswith("GZ") and code[-3:].isdigit(): # 注意国证系列指数的代码里可能包含多个字母! _from = "GZ" elif code.startswith("HZ") and code[2:].isdigit(): _from = "HZ" elif code.startswith("ESCI") and code[4:].isdigit(): _from = "ES" elif code.startswith("yc-companies/") or code.startswith("yc-indices/"): _from = "ycharts" params = code.split("/") code = params[1] category = params[0].split("-")[1] if len(params) == 3: metric = params[2] else: if category == "companies": metric = "price" elif category == "indices": metric = "level" elif len(code.split("-")) >= 2 and len(code.split("-")[0]) <= 3: # peb-000807.XSHG _from = code.split("-")[0] code = "-".join(code.split("-")[1:]) elif len(code[1:].split("/")) == 2: _from = "cninvesting" code = get_investing_id(code) else: _from = "xueqiu" # 美股代码 count = (today_obj() - start_obj).days + 1 start_str = start_obj.strftime("%Y/%m/%d") end_str = end_obj.strftime("%Y/%m/%d") if _from in ["cninvesting", "investing", "default", "IN"]: df = get_historical_fromcninvesting(code, start_str, end_str) df = prettify(df) elif _from in ["xueqiu", "xq", "snowball", "XQ"]: code, type_ = decouple_code(code) df = get_historical_fromxq(code, count, type_=type_) df = prettify(df) elif _from in ["zhongjianjia", "zjj", "chinamoney", "ZJJ"]: df = get_rmb(start, end, prev, currency=code) elif _from in ["ttjj", "tiantianjijin", "xalpha", "eastmoney"]: if code.startswith("F96"): df = get_historical_from_ttjj_oversea(code, start=start, end=end) else: df = get_fund(code) elif _from == "peb": if ( code.startswith("SH000") or code.startswith("SZ399") or code.startswith("399") or code.startswith("000") ): df = _get_peb_range(code=code, start=start_str, end=end_str) elif code.startswith("F"): df = get_fund_peb_range(code=code, start=start, end=end) else: df = get_stock_peb_range(code=code, start=start, end=end, wrapper=True) elif _from == "iw": df = _get_index_weight_range(code=code, start=start_str, end=end_str) elif _from == "fs": df = get_fundshare_byjq(code, start=start, end=end) elif _from == "SP": df = get_historical_fromsp(code, start=start, end=end) elif _from == "SPC": df = get_historical_fromsp(code[3:], start=start, end=end, region="chinese") elif _from == "BB": df = get_historical_frombb(code, start=start, end=end) elif _from == "ZZ": df = get_historical_fromzzindex(code, start=start, end=end) elif _from == "GZ": df = get_historical_fromgzindex(code, start=start, end=end) elif _from == "HZ": df = get_historical_fromhzindex(code, start=start, end=end) elif _from == "ES": df = get_historical_fromesunny(code, start=start, end=end) elif _from == "B": df = get_bond_rates_range(code, start=start, end=end) elif _from == "fu": code = code.replace(".", "-") df = get_futu_historical(code, start=start, end=end) elif _from == "ycharts": df = get_historical_fromycharts( code, start=start_obj.strftime("%m/%d/%Y"), end=end_obj.strftime("%m/%d/%Y"), category=category, metric=metric, ) elif _from == "sw": df = get_sw_from_jq(code, start=start, end=end) elif _from == "teb": df = get_teb_range(code, start=start, end=end) elif _from in ["pt", "portfolio"]: df = get_portfolio_fromttjj(code, start=start, end=end) elif _from == "YH": df = get_historical_fromyh(code, start=start, end=end) elif _from in ["FT", "FTI"]: df = get_historical_fromft(code, start=start, end=end) elif _from == "FTE": df = get_historical_fromft(code, start=start, end=end, _type="equities") elif _from == "FTB": df = get_historical_fromft(code, start=start, end=end, _type="bonds") elif _from == "FTF": df = get_historical_fromft(code, start=start, end=end, _type="funds") elif _from == "FTX": df = get_historical_fromft(code, start=start, end=end, _type="currencies") elif _from == "FTC": df = get_historical_fromft(code, start=start, end=end, _type="commodities") elif _from == "INA": # investing app code = get_investing_id(code, app=True) df = get_historical_fromcninvesting(code, start_str, end_str, app=True) df = prettify(df) elif _from == "mcy": df = get_macro(code, start=start[:4], end=end[:4], datecol="stat_year") elif _from == "mcq": df = get_macro(code, start=start, end=end, datecol="stat_quarter") elif _from == "mcm": df = get_macro(code, start=start, end=end, datecol="stat_month") elif _from == "mcd": df = get_macro(code, start=start, end=end, datecol="day") else: raise ParserFailure("no such data source: %s" % _from) if wrapper or len(df) == 0: return df else: df = df[df.date <= end_str] df = df[df.date >= start_str] return df def get_xueqiu_rt(code, token="a664afb60c7036c7947578ac1a5860c4cfb6b3b5"): if code.startswith("HK") and code[2:].isdigit(): code = code[2:] url = "https://stock.xueqiu.com/v5/stock/quote.json?symbol={code}&extend=detail" r = rget_json( url.format(code=code), cookies={"xq_a_token": token}, headers={"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)"}, ) n = r["data"]["quote"]["name"] q = r["data"]["quote"]["current"] try: q = _float(q) except TypeError: # 针对雪球实时在9点后开盘前可能出现其他情形的fixup, 效果待 check # 现在的怀疑是在9am 到9:15 am, 雪球 API current 字段返回 Null q = _float(r["data"]["quote"]["last_close"]) q_ext = r["data"]["quote"].get("current_ext", None) percent = r["data"]["quote"]["percent"] try: percent = _float(percent) except: pass currency = r["data"]["quote"]["currency"] market = r["data"]["market"]["region"] timestr = dt.datetime.fromtimestamp(r["data"]["quote"]["time"] / 1000).strftime( "%Y-%m-%d %H:%M:%S" ) if r["data"]["quote"].get("timestamp_ext", None): time_ext = dt.datetime.fromtimestamp( r["data"]["quote"]["timestamp_ext"] / 1000 ).strftime("%Y-%m-%d %H:%M:%S") else: time_ext = None share = r["data"]["quote"]["total_shares"] fshare = r["data"]["quote"]["float_shares"] volume = r["data"]["quote"]["volume"] return { "name": n, "current": q, "percent": percent, "current_ext": _float(q_ext) if q_ext else None, "currency": currency, "market": market, # HK, US, CN "time": timestr, "time_ext": time_ext, "totshare": share, "floatshare": fshare, "volume": volume, } def get_cninvesting_rt(suburl, app=False): if not app: url = "https://cn.investing.com" else: url = "https://cnappapi.investing.com" if not suburl.startswith("/"): url += "/" url += suburl if not app: headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36" } else: headers = { "Accept": "*/*", "Accept-Encoding": "gzip", "Accept-Language": "zh-cn", "Cache-Control": "no-cache", "Connection": "keep-alive", "User-Agent": "Investing.China/0.0.3 CFNetwork/1121.2.2 Darwin/19.3.0", "ccode": "CN", #'ccode_time': '1585551041.986028', "x-app-ver": "117", "x-meta-ver": "14", "x-os": "ios", "x-uuid": str(uuid4()), "Host": "cn.investing.com", "X-Requested-With": "XMLHttpRequest", } r = rget( url, headers=headers, ) s = BeautifulSoup(r.text, "lxml") last_last = s.find("span", id="last_last") q = _float(last_last.string) name = s.find("h1").string.strip() ind = 0 timestr = s.select('span[class*="ClockBigIcon"]+span')[0].text l = s.find("div", class_="lighterGrayFont").contents for i, c in enumerate(l): if isinstance(c, str) and c.strip() == "货币": ind = i break if ind == 0: currency = None else: currency = l[ind - 1].string percent = _float( s.find("span", attrs={"dir": "ltr", "class": "parentheses"}).string[:-1] ) panhou = s.find("div", class_="afterHoursInfo") if panhou: q_ext = _float(panhou.find("span").string) else: q_ext = None market = None for span in s.findAll("span", class_="elp"): if span.find("a") and span.find("a")["href"].startswith("/markets"): market = span.string market = region_trans.get(market, market) time_ext = s.select("div[class~=lastUpdated]") if time_ext: time_ext = time_ext[0].text.strip() else: time_ext = None d = { "name": name, "current": q, "current_ext": q_ext, "time": timestr, "time_ext": time_ext, "currency": currency, "percent": percent, "market": market, } if suburl.startswith("commodities"): # 商品期货展期日 try: d["rollover"] = s.select("span[class*=float_lang_base_2]")[10].string d["lastrollover"] = s.select("span[class*=float_lang_base_2]")[13].string except (ValueError, IndexError, AttributeError): logger.warning("%s cannot extract rollover date" % suburl) # in case some commodities with strong page structure return d def get_rt_from_sina(code): if ( code.startswith("SH") or code.startswith("SZ") or code.startswith("HK") ) and code[2:].isdigit(): tinycode = code[:2].lower() + code[2:] if code.startswith("HK"): # 港股额外要求实时 tinycode = "rt_" + tinycode else: # 美股 tinycode = "gb_" if code.startswith("."): code = code[1:] tinycode += code.lower() r = rget("https://hq.sinajs.cn/list={tinycode}".format(tinycode=tinycode)) l = r.text.split("=")[1].split(",") d = {} d["name"] = l[0].strip('"') if ( code.startswith("SH") or code.startswith("SZ") or code.startswith("HK") ) and code[2:].isdigit(): # TODO: 20200819: API seems changed a bit, index shift? # or things may get zero when the market is closed? if code.startswith("HK"): d["current"] = float(l[9]) # 英文股票名称占位 d["currency"] = "HKD" d["percent"] = round(float(l[8]), 2) d["market"] = "HK" d["time"] = l[17] + " " + l[18] d["current_ext"] = None else: # A 股 d["current"] = float(l[3]) d["currency"] = "CNY" d["percent"] = round((float(l[3]) / float(l[2]) - 1) * 100, 2) d["market"] = "CN" d["time"] = l[-4] + " " + l[-3] for i in range(10, 19)[::2]: d["buy" + str(int((i - 8) / 2))] = (l[i + 1], l[i]) for i in range(20, 29)[::2]: d["sell" + str(int((i - 18) / 2))] = (l[i + 1], l[i]) d["current_ext"] = None else: d["currency"] = "USD" d["current"] = float(l[1]) d["percent"] = float(l[2]) d["current_ext"] = _float(l[21]) if _float(l[21]) > 0 else None d["market"] = "US" d["time"] = l[3] return d def make_ft_url(code, _type="indices"): if _type == "indices": url = "https://markets.ft.com/data/indices/tearsheet/summary?s={code}".format( code=code ) elif _type == "commodities": url = ( "https://markets.ft.com/data/commodities/tearsheet/summary?c={code}".format( code=code ) ) elif _type == "currencies": url = ( "https://markets.ft.com/data/currencies/tearsheet/summary?s={code}".format( code=code ) ) elif _type == "funds": url = "https://markets.ft.com/data/funds/tearsheet/summary?s={code}".format( code=code ) elif _type == "equities": url = "https://markets.ft.com/data/equities/tearsheet/summary?s={code}".format( code=code ) elif _type == "bonds": url = "https://markets.ft.com/data/bonds/tearsheet/summary?s={code}".format( code=code ) else: raise ParserFailure("no reconginzed type for ft datasource: %s" % _type) return url @lru_cache(maxsize=1024) def get_ft_id(code, _type="indices"): url = make_ft_url(code, _type=_type) r = rget(url) b = BeautifulSoup(r.text, "lxml") return eval( b.find("section", class_="mod-tearsheet-add-to-watchlist")["data-mod-config"] )["xid"] def get_rt_from_ft(code, _type="indices"): url = make_ft_url(code, _type=_type) r = rget(url) b = BeautifulSoup(r.text, "lxml") d = {} d["name"] = b.find("h1").string d["current"] = _float(b.find("span", class_="mod-ui-data-list__value").string) d["percent"] = _float( b.select("span[class^='mod-format--']")[0].text.split("/")[-1].strip()[:-1] ) d["current_ext"] = None d["market"] = None d["currency"] = b.find("span", class_="mod-ui-data-list__label").string.split("(")[ 1 ][:-1] d["time"] = b.find("div", class_="mod-disclaimer").string return d def get_rt_from_ycharts(code): if code.startswith("yc-"): code = code[3:] url = "https://ycharts.com/" + code r = rget(url) s = BeautifulSoup(r.text, "lxml") qdiv = s.select("div.index-rank.col-auto") # current spans = [s for s in qdiv[0].contents if s != "\n" and s.contents] d = {} d["name"] = s.select("h1,h3[class=securityName]")[0].text.strip() d["current"], d["percent"] = ( _float(spans[0].string), # current, _float(spans[1].contents[-2].string[1:-1]), # percent ) l = [ c.strip() for c in s.select("span[class=index-info]")[0].string.split("\n") if c.strip() ] d["time"] = l[1] d["currency"] = l[0].split(" ")[0].strip() d["market"] = None return d @lru_cache_time(ttl=300, maxsize=512) def get_newest_netvalue(code): code = code[1:] r = rget("http://fund.eastmoney.com/{code}.html".format(code=code)) s = BeautifulSoup(r.text, "lxml") return ( float( s.findAll("dd", class_="dataNums")[1] .find("span", class_="ui-font-large") .string ), str(s.findAll("dt")[1]).split("(")[1].split(")")[0][7:], ) @lru_cache(maxsize=512) def get_hkfcode(code): if code.startswith("F"): code = code[1:] page = rget("http://overseas.1234567.com.cn/{code}".format(code=code)).text page.find("hkfcode") hkfcode = ( page[page.find("hkfcode") :] .split("=")[1] .split(";")[0] .lstrip() .lstrip("'") .strip("'") ) return hkfcode def get_rt_from_ttjj_oversea(code): if code.startswith("F"): code = code[1:] if not code.startswith("96"): raise ValueError("%s is not an oversea fund" % code) r = rget("http://overseas.1234567.com.cn/{code}.html".format(code=code)) r.encoding = "utf-8" s = BeautifulSoup(r.text, "lxml") start = s.select("dl.dataItem02")[0].text start = start.split("(")[1].split(")")[0] name = s.select("div[class='fundDetail-tit']")[0].text.split("(")[0].strip() name = name.split("(")[0].strip() value = _float(s.select("span.ui-font-large.ui-num")[0].text) date = ( s.select("dl[class='dataItem01']")[0] .find("p") .text.split("(")[-1] .split(")")[0] ) infol = [ r for r in s.select("div[class='infoOfFund']")[0].text.split("\n") if r.strip() ] return { "name": name, "time": date, "current": value, "market": "CN", "currency": None, # 很可能存在非人民币计价的互认基金 "current_ext": None, "type": infol[0].split(":")[1].strip(), "scale": infol[1].split(":")[1].strip(), "manager": infol[2].split(":")[1].strip(), "startdate": start, } @lru_cache_time(ttl=600, maxsize=512) def get_rt_from_ttjj(code): code = code[1:] if code.startswith("96"): return get_rt_from_ttjj_oversea(code) r = rget("http://fund.eastmoney.com/{code}.html".format(code=code)) r.encoding = "utf-8" s = BeautifulSoup(r.text, "lxml") name = s.select("div[style='float: left']")[0].text.split("(")[0] if s.findAll("dd", class_="dataNums")[1].find( "span", class_="ui-font-large" ): # 非货币基金 value, date = ( float( s.findAll("dd", class_="dataNums")[1] .find("span", class_="ui-font-large") .string ), str(s.findAll("dt")[1]).split("(")[1].split(")")[0][7:], ) estimate = s.select("span[id=gz_gsz]")[0].text # after loading if estimate == "--": gsz = rget( "http://fundgz.1234567.com.cn/js/{code}.js".format(code=code), headers={ "Host": "fundgz.1234567.com.cn", "Referer": "http://fund.eastmoney.com/", }, ) try: # in case eval error gsz_dict = eval(gsz.text[8:-2]) estimate = _float(gsz_dict["gsz"]) estimate_time = gsz_dict["gztime"] except: estimate = None else: try: estimate = _float(estimate) except ValueError: logger.warning("unrecognized estimate netvalue %s" % estimate) estimate = None else: value, date = ( s.findAll("dd", class_="dataNums")[1].text, str(s.findAll("dt")[1]).split("(")[1].split(")")[0], ) estimate = None status = s.select("span[class='staticCell']")[0].text.strip() tb = s.select("div.infoOfFund > table >tr>td") infol = [i.text for i in tb] try: estimate_time except NameError: estimate_time = None return { "name": name, "time": date, "current": value, "market": "CN", "currency": "CNY", "current_ext": None, "status": status, "type": infol[0].split(":")[1].split("\xa0")[0], "scale": infol[1].split(":")[1], "manager": infol[2].split(":")[1], "company": infol[4].split(":")[1], "estimate": estimate, "estimate_time": estimate_time, } # 是否有美元份额计价的基金会出问题? @lru_cache(2048) def get_fund_type(code): code = code[-6:] t = get_rt("F" + code)["type"] if t in ["联接基金", "股票指数"] or t.startswith("ETF"): return "指数基金" elif t.startswith("QDII"): return "QDII" elif t.startswith("股票"): return "股票基金" elif t.startswith("混合"): return "混合基金" elif t.startswith("债券"): return "债券基金" elif t.startswith("货币"): return "货币基金" else: return "其他" def get_rt( code, _from=None, double_check=False, double_check_threhold=0.005, handler=True ): # 对于一些标的,get_rt 的主任务可能不是 current 价格,而是去拿 market currency 这些元数据 # 现在用的新浪实时数据源延迟严重, double check 并不靠谱,港股数据似乎有15分钟延迟(已解决) # 雪球实时和新浪实时在9:00之后一段时间可能都有问题 # FT 数据源有10到20分钟的延迟 if handler: if getattr(thismodule, "get_rt_handler", None): args = inspect.getargvalues(inspect.currentframe()) f = getattr(thismodule, "get_rt_handler") fr = f(**args.locals) if fr: return fr if not _from: # if code.startswith("HK") and code[2:].isdigit(): # _from = "xueqiu" if code.startswith("yc-"): _from = "ycharts" elif len(code.split("-")) >= 2 and len(code.split("-")[0]) <= 3: _from = code.split("-")[0] code = "-".join(code.split("-")[1:]) elif (code.startswith("F") or code.startswith("T")) and code[1:].isdigit(): _from = "ttjj" elif len(code.split("/")) > 1: _from = "investing" else: # 默认启用雪球实时,新浪纯指数行情不完整 _from = "xueqiu" if _from in ["cninvesting", "investing"]: try: return get_cninvesting_rt(code) except Exception as e: logger.warning( "Fails due to %s, now trying app source of investing.com" % e.args[0] ) return get_cninvesting_rt(code, app=True) elif double_check and _from in ["xueqiu", "sina"]: r1 = get_xueqiu_rt(code, token=get_token()) r2 = get_rt_from_sina(code) if abs(r1["current"] / r2["current"] - 1) > double_check_threhold: raise DataPossiblyWrong("realtime data unmatch for %s" % code) return r2 elif _from in ["xueqiu", "xq", "snowball"]: try: return get_xueqiu_rt(code, token=get_token()) except (IndexError, ValueError, AttributeError, TypeError) as e: # 默认雪球实时引入备份机制 logging.warning( "Fails due to %s, now trying backup data source from sina" % e.args[0] ) return get_rt_from_sina(code) elif _from in ["sina", "sn", "xinlang"]: try: return get_rt_from_sina(code) except (IndexError, ValueError, AttributeError, TypeError) as e: # 默认雪球实时引入备份机制 logging.warning( "Fails due to %s, now trying backup data source from xueqiu" % e.args[0] ) return get_xueqiu_rt(code, token=get_token()) elif _from in ["ttjj"]: return get_rt_from_ttjj(code) elif _from in ["FT", "ft", "FTI"]: return get_rt_from_ft(code) elif _from == "FTE": return get_rt_from_ft(code, _type="equities") elif _from == "FTB": return get_rt_from_ft(code, _type="bonds") elif _from == "FTF": return get_rt_from_ft(code, _type="funds") elif _from == "FTX": return get_rt_from_ft(code, _type="currencies") elif _from == "FTC": return get_rt_from_ft(code, _type="commodities") elif _from in ["INA"]: # investing app return get_cninvesting_rt(code, app=True) elif _from in ["yc", "ycharts"]: return get_rt_from_ycharts(code) else: raise ParserFailure("unrecoginzed _from for %s" % _from) get_realtime = get_rt get_now = get_rt _cached_data = {} def reset_cache(): global _cached_data _cached_data = {} setattr(thismodule, "cached_dict", {}) def cached(s): def cached_start(f): @wraps(f) def wrapper(*args, **kws): print("cached function is deprecated, please instead use cachedio") if args: code = args[0] else: code = kws.get("code") start = kws.get("start", None) end = kws.get("end", None) prev = kws.get("prev", None) if not prev: prev = 365 if not end: end_obj = today_obj() else: end_obj = dstr2dobj(end) if not start: start_obj = end_obj - dt.timedelta(prev) else: start_obj = dstr2dobj(start) start_str = start_obj.strftime("%Y%m%d") end_str = end_obj.strftime("%Y%m%d") kws["start"] = s kws["end"] = dt.datetime.now().strftime("%Y%m%d") global _cached_data _cached_data.setdefault(s, {}) if code not in _cached_data[s]: df = f(*args, **kws) # print("cached %s" % code) _cached_data[s][code] = df else: pass # print("directly call cache") df = _cached_data[s][code] df = df[df["date"] <= end_str] df = df[df["date"] >= start_str] return df return wrapper return cached_start def cachedio(**ioconf): def cached(f): @wraps(f) def wrapper(*args, **kws): if args: code = args[0] else: code = kws.get("code") date = ioconf.get("date", "date") # 没利用上这个栏的名字变化 precached = ioconf.get("precached", None) precached = kws.get("precached", precached) key = kws.get("key", code) key = key.replace("/", " ") key_func = ioconf.get("key_func", None) key_func = ioconf.get("keyfunc", key_func) if key_func is not None: key = key_func(key) defaultend = ioconf.get("defaultend", today_obj) defaultend = ioconf.get("default_end", defaultend) defaultprev = ioconf.get("defaultprev", 365) defaultprev = ioconf.get("default_prev", defaultprev) if isinstance(defaultend, str): defaultend = defaultend.replace("/", "").replace("-", "") defaultend = dt.datetime.strptime(defaultend, "%Y%m%d") if callable(defaultend): defaultend = defaultend() start = kws.get("start", None) end = kws.get("end", None) prev = kws.get("prev", None) prefix = ioconf.get("prefix", "") key = prefix + key if precached: precached = precached.replace("/", "").replace("-", "") precached_obj = dt.datetime.strptime(precached, "%Y%m%d") if not prev: prev = defaultprev if not end: end_obj = defaultend else: end_obj = dt.datetime.strptime( end.replace("/", "").replace("-", ""), "%Y%m%d" ) if not start: start_obj = end_obj - dt.timedelta(days=prev) else: start_obj = dt.datetime.strptime( start.replace("/", "").replace("-", ""), "%Y%m%d" ) start_str = start_obj.strftime("%Y%m%d") end_str = end_obj.strftime("%Y%m%d") backend = ioconf.get("backend") backend = kws.get("backend", backend) # if backend == "sql": # reserved for case insensitive database settings # key = key.lower() refresh = ioconf.get("refresh", False) refresh = kws.get("refresh", refresh) fetchonly = ioconf.get("fetchonly", False) fetchonly = ioconf.get("fetch_only", fetchonly) fetchonly = kws.get("fetchonly", fetchonly) fetchonly = kws.get("fetch_only", fetchonly) path = ioconf.get("path") path = kws.get("path", path) kws["start"] = start_str kws["end"] = end_str if not backend: df = f(*args, **kws) df = df[df["date"] <= kws["end"]] df = df[df["date"] >= kws["start"]] return df else: if backend == "csv": key = key + ".csv" if not getattr(thismodule, "cached_dict", None): setattr(thismodule, "cached_dict", {}) if refresh: is_changed = True df0 = f(*args, **kws) else: # non refresh try: if backend == "csv": if key in getattr(thismodule, "cached_dict"): # 即使硬盘级别的缓存,也有内存层,加快读写速度 df0 = getattr(thismodule, "cached_dict")[key] else: df0 = pd.read_csv(os.path.join(path, key)) elif backend == "sql": if key in getattr(thismodule, "cached_dict"): df0 = getattr(thismodule, "cached_dict")[key] else: df0 = pd.read_sql(key, path) elif backend == "memory": df0 = getattr(thismodule, "cached_dict")[key] else: raise ValueError("no %s option for backend" % backend) df0[date] = pd.to_datetime(df0[date]) # 向前延拓 is_changed = False if df0.iloc[0][date] > start_obj and not fetchonly: kws["start"] = start_str kws["end"] = ( df0.iloc[0][date] - pd.Timedelta(days=1) ).strftime("%Y%m%d") if has_weekday(kws["start"], kws["end"]): # 考虑到海外市场的不同情况,不用 opendate 判断,采取保守型判别 df1 = f(*args, **kws) if df1 is not None and len(df1) > 0: df1 = df1[df1["date"] <= kws["end"]] if df1 is not None and len(df1) > 0: is_changed = True df0 = df1.append(df0, ignore_index=True, sort=False) # 向后延拓 if df0.iloc[-1][date] < end_obj and not fetchonly: nextday_str = ( df0.iloc[-1][date] + dt.timedelta(days=1) ).strftime("%Y%m%d") if len(df0[df0["date"] == df0.iloc[-1]["date"]]) == 1: kws["start"] = (df0.iloc[-1][date]).strftime("%Y%m%d") else: # 单日多行的表默认最后一日是准确的,不再刷新了 kws["start"] = nextday_str kws["end"] = end_str if has_weekday(nextday_str, kws["end"]): # 新更新的日期里有工作日 df2 = f(*args, **kws) if df2 is not None and len(df2) > 0: df2 = df2[df2["date"] >= kws["start"]] if df2 is not None and len(df2) > 0: is_changed = True if ( len(df0[df0["date"] == df0.iloc[-1]["date"]]) == 1 ): df0 = df0.iloc[:-1] df0 = df0.append(df2, ignore_index=True, sort=False) # 注意这里抹去更新了原有最后一天的缓存,这是因为日线最新一天可能有实时数据污染 except (FileNotFoundError, exc.ProgrammingError, KeyError) as e: if fetchonly: logger.error( "no cache in backend for %s but you insist `fetchonly`" % code ) raise e if precached: if start_obj > precached_obj: kws["start"] = precached if end_obj < today_obj(): kws["end"] = ( today_obj() - dt.timedelta(days=1) ).strftime("%Y%m%d") is_changed = True df0 = f(*args, **kws) if df0 is not None and len(df0) > 0 and is_changed: if backend == "csv": df0.to_csv(os.path.join(path, key), index=False) elif backend == "sql": df0.to_sql(key, con=path, if_exists="replace", index=False) # elif backend == "memory": # 总是刷新内存层,即使是硬盘缓存 d = getattr(thismodule, "cached_dict") d[key] = df0 if df0 is not None and len(df0) > 0: df0 = df0[df0["date"] <= end_str] df0 = df0[df0["date"] >= start_str] return df0 return wrapper return cached def fetch_backend(key): prefix = ioconf.get("prefix", "") key = prefix + key backend = ioconf.get("backend") path = ioconf.get("path") if backend == "csv": key = key + ".csv" try: if backend == "csv": df0 = pd.read_csv(os.path.join(path, key)) elif backend == "sql": df0 = pd.read_sql(key, path) else: raise ValueError("no %s option for backend" % backend) return df0 except (FileNotFoundError, exc.ProgrammingError, KeyError): return None def save_backend(key, df, mode="a", header=False): prefix = ioconf.get("prefix", "") key = prefix + key backend = ioconf.get("backend") path = ioconf.get("path") if backend == "csv": key = key + ".csv" if backend == "csv": if mode == "a": df.to_csv(os.path.join(path, key), index=False, header=header, mode=mode) else: df.to_csv(os.path.join(path, key), index=False, mode=mode) elif backend == "sql": if mode == "a": mode = "append" else: mode = "replace" df.to_sql(key, con=path, if_exists=mode, index=False) else: raise ValueError("no %s option for backend" % backend) logger.debug("%s saved into backend successfully" % key) def check_cache(*args, omit_lines=0, **kws): if omit_lines == 0: assert ( _get_daily(*args, wrapper=False, **kws) .reset_index(drop=True) .equals(get_daily(*args, **kws).reset_index(drop=True)) ) else: assert ( _get_daily(*args, wrapper=False, **kws) .reset_index(drop=True)[:-omit_lines] .equals(get_daily(*args, **kws).reset_index(drop=True)[:-omit_lines]) ) @data_source("jq") def _get_index_weight_range(code, start, end): if len(code.split(".")) != 2: code = _inverse_convert_code(code) start_obj = dt.datetime.strptime(start.replace("-", "").replace("/", ""), "%Y%m%d") end_obj = dt.datetime.strptime(end.replace("-", "").replace("/", ""), "%Y%m%d") start_m = start_obj.replace(day=1) if start_m < start_obj: start_m = start_m + relativedelta(months=1) end_m = end_obj.replace(day=1) if end_obj < end_m: end_m = end_m - relativedelta(months=1) d = start_m df = pd.DataFrame({"code": [], "weight": [], "display_name": [], "date": []}) while True: if d > end_m: df["date"] = pd.to_datetime(df["date"]) return df logger.debug("fetch index weight on %s for %s" % (d, code)) df0 = get_index_weights(index_id=code, date=d.strftime("%Y-%m-%d")) df0["code"] = df0.index df = df.append(df0, ignore_index=True, sort=False) d = d + relativedelta(months=1) @data_source("jq") def _get_peb_range(code, start, end): # 盈利,净资产,总市值 if len(code.split(".")) != 2: code = _inverse_convert_code(code) data = {"date": [], "pe": [], "pb": []} for d in pd.date_range(start=start, end=end, freq="W-FRI"): data["date"].append(d) logger.debug("compute pe pb on %s" % d) r = get_peb(code, date=d.strftime("%Y-%m-%d")) data["pe"].append(r["pe"]) data["pb"].append(r["pb"]) return pd.DataFrame(data) def get_stock_peb_range(code, start, end, wrapper=False): if code.startswith("HK") and code[2:].isdigit(): code = code[2:] count = (today_obj() - dt.datetime.strptime(start, "%Y%m%d")).days df = get_historical_fromxq(code, count, full=True) df = df[["date", "pe", "pb", "ps"]] if not wrapper: df = df[df["date"] >= start] df = df[df["date"] <= end] return df @lru_cache() def ttjjcode(code): code = code.strip() if code.endswith(".HK"): return "HK" + code[:-3] elif code.endswith(".US"): return code[:-3] elif code.isdigit() and len(code) == 5: return "HK" + code elif code.isdigit() and len(code) == 6: if ( code.startswith("16") or code.startswith("15") or code.startswith("12") or code.startswith("0") or code.startswith("3") ): # 注意这里只能对应个股,指数代码有重叠没有办法的事 return "SZ" + code elif code.startswith("5") or code.startswith("6") or code.startswith("11"): return "SH" + code else: logger.warning("unrecognized code format %s" % code) return "0" else: logger.info("not so sure about code format %s, taken as US stock" % code) return code def get_fund_peb(code, date, threhold=0.3): if code.startswith("F"): code = code[1:] date = date.replace("/", "").replace("-", "") d = dt.datetime.strptime(date, "%Y%m%d") if d.month > 3 and d.month < 8: year = d.year - 1 season = 4 elif d.month <= 3: year = d.year - 1 season = 2 else: year = d.year season = 2 # season 只选 2,4, 具有更详细的持仓信息 df = get_fund_holdings(code, year, season) if df is None: if season == 4: season = 2 else: year -= 1 season = 4 df = get_fund_holdings(code, year, season) if df is None: logger.warning("%s seems has no holdings data in this time %s" % (code, year)) return {"pe": None, "pb": None} df = df[df["ratio"] >= threhold] df["scode"] = df["code"].apply(ttjjcode) df = df[df["scode"] != "0"] if len(df) == 0: return {"pe": None, "pb": None} pel, pbl = [], [] for i, r in df.iterrows(): try: fdf = get_daily("peb-" + r["scode"], end=date, prev=60) if len(fdf) == 0: # 已退市或改名 logger.warning("%s: 无法获取,可能已退市,当时休市或改名" % r["scode"]) pel.append(None) pbl.append(None) else: fdf = fdf.iloc[-1] pel.append(fdf["pe"]) pbl.append(fdf["pb"]) except (KeyError, TypeError, IndexError) as e: logger.warning( "%s: 获取历史估值出现问题: %s, 可能由于网站故障或股票代码非中美市场" % (r["scode"], e.args[0]) ) pel.append(None) pbl.append(None) df["pe"] = pel df["pb"] = pbl r = {} pedf = df[~pd.isna(df["pe"])] pbdf = df[~pd.isna(df["pb"])] if len(pbdf) < 0.5 * len(df): # 有时候会有个别标的有pb值 r["pb"] = None else: pbdf["b"] = pbdf["ratio"] / (pbdf["pb"] + 0.000001) r["pb"] = pbdf.ratio.sum() / pbdf.b.sum() if len(pedf) == 0: r["pe"] = None else: pedf["e"] = pedf["ratio"] / (pedf["pe"] + 0.000001) r["pe"] = pedf.ratio.sum() / pedf.e.sum() return r def get_fund_peb_range(code, start, end): if code.startswith("F"): code = code[1:] data = {"date": [], "pe": [], "pb": []} for d in pd.date_range(start=start, end=end, freq="W-FRI"): data["date"].append(d) r = get_fund_peb(code, date=d.strftime("%Y-%m-%d")) data["pe"].append(r["pe"]) data["pb"].append(r["pb"]) return pd.DataFrame(data) def set_backend(**ioconf): if not ioconf: ioconf = {"backend": "memory"} get_daily = cachedio(**ioconf)(_get_daily) prefix = ioconf.get("prefix", "") ioconf["prefix"] = "iw-" + prefix get_index_weight_range = cachedio(**ioconf)(_get_index_weight_range) ioconf["prefix"] = "peb-" + prefix get_peb_range = cachedio(**ioconf)(_get_peb_range) setattr(thismodule, "get_daily", get_daily) setattr(xamodule, "get_daily", get_daily) setattr(thismodule, "get_index_weight_range", get_index_weight_range) setattr(thismodule, "get_peb_range", get_peb_range) ioconf["prefix"] = prefix setattr(thismodule, "ioconf", ioconf) set_backend() @data_source("jq") def get_peb(index, date=None, table=False): if len(index.split(".")) == 2: index = _convert_code(index) middle = dt.datetime.strptime( date.replace("/", "").replace("-", ""), "%Y%m%d" ).replace(day=1) iwdf = get_index_weight_range( index, start=(middle - dt.timedelta(days=10)).strftime("%Y-%m-%d"), end=(middle + dt.timedelta(days=6)).strftime("%Y-%m-%d"), ) q = query(valuation).filter(valuation.code.in_(list(iwdf.code))) logger.debug("get_fundamentals on %s" % (date)) df = get_fundamentals(q, date=date) df = df.merge(iwdf, on="code") df["e"] = df["weight"] / df["pe_ratio"] df["b"] = df["weight"] / df["pb_ratio"] df["p"] = df["weight"] tote = df.e.sum() totb = df.b.sum() if table: return df return { "pe": (round(100.0 / tote, 3) if tote != 0 else np.inf), "pb": (round(100.0 / totb, 3) if totb != 0 else np.inf), } @data_source("jq") def get_sw_from_jq(code, start=None, end=None, **kws): logger.debug("get sw data of %s" % code) df = finance.run_query( query(finance.SW1_DAILY_VALUATION) .filter(finance.SW1_DAILY_VALUATION.date >= start) .filter(finance.SW1_DAILY_VALUATION.date <= end) .filter(finance.SW1_DAILY_VALUATION.code == code) .order_by(finance.SW1_DAILY_VALUATION.date.asc()) ) df["date"] = pd.to_datetime(df["date"]) return df @data_source("jq") def get_teb(code, date): if len(code.split(".")) != 2: code = _inverse_convert_code(code) sl = get_index_stocks(code, date=date) logger.debug("get fundamentals from jq for %s" % code) df = get_fundamentals(query(valuation).filter(valuation.code.in_(sl)), date=date) df["e"] = df["market_cap"] / df["pe_ratio"] df["b"] = df["market_cap"] / df["pb_ratio"] return {"e": df["e"].sum(), "b": df["b"].sum(), "m": df["market_cap"].sum()} # 亿人民币 def get_teb_range(code, start, end, freq="W-FRI"): if len(code.split(".")) != 2: code = _inverse_convert_code(code) data = {"date": [], "e": [], "b": [], "m": []} for d in pd.date_range(start, end, freq=freq): data["date"].append(d) r = get_teb(code, d.strftime("%Y-%m-%d")) data["e"].append(r["e"]) data["b"].append(r["b"]) data["m"].append(r["m"]) df = pd.DataFrame(data) return df def _convert_code(code): no, mk = code.split(".") if mk == "XSHG": return "SH" + no elif mk == "XSHE": return "SZ" + no def _inverse_convert_code(code): if code.startswith("SH"): return code[2:] + ".XSHG" elif code.startswith("SZ"): return code[2:] + ".XSHE" @lru_cache_time(ttl=60, maxsize=512) def get_bar( code, prev=24, interval=3600, _from=None, handler=True, start=None, end=None ): if handler: if getattr(thismodule, "get_bar_handler", None): args = inspect.getargvalues(inspect.currentframe()) f = getattr(thismodule, "get_bar_handler") fr = f(**args.locals) if fr is not None: return fr if not _from: if ( (start is not None) and (end is not None) and (code.startswith("SH") or code.startswith("SZ")) ): _from = "jq" elif code.startswith("SH") or code.startswith("SZ"): _from = "xueqiu" elif code.isdigit(): _from = "cninvesting" elif code.startswith("HK") and code[2:7].isdigit(): _from = "xueqiu" code = code[2:] elif len(code.split("-")) >= 2 and len(code.split("-")[0]) <= 3: _from = code.split("-")[0] code = "-".join(code.split("-")[1:]) elif len(code.split("/")) > 1: _from = "cninvesting" code = get_investing_id(code) else: _from = "xueqiu" # 美股 if _from in ["xq", "xueqiu", "XQ"]: return get_bar_fromxq(code, prev, interval) elif _from in ["IN", "cninvesting", "investing"]: return get_bar_frominvesting(code, prev, interval) elif _from in ["INA"]: return get_bar_frominvesting(code, prev, interval) # 这里 investing app 源是 404,只能用网页源 elif _from in ["jq"]: code, type_ = decouple_code(code) # 关于复权,聚宽各个时间密度的数据都有复权,雪球源日线以上的高频数据没有复权 type_map = {"after": "post", "before": "pre", "normal": None} return get_bar_fromjq( code, start=start, end=end, interval=interval, fq=type_map[type_] ) elif _from in ["wsj"]: return get_bar_fromwsj(code, interval=interval)[-prev:] else: raise ParserFailure("unrecoginized _from %s" % _from) @data_source("jq") def get_bar_fromjq(code, start, end, interval, fq="pre"): code = _inverse_convert_code(code) trans = { "60": "1m", "120": "2m", "300": "5m", "900": "15m", "1800": "30m", "3600": "60m", "7200": "120m", "86400": "daily", } interval = trans.get(str(interval), interval) logger.debug("calling ``get_price`` from jq with %s" % code) return get_price(code, start_date=start, end_date=end, frequency=interval, fq=fq) def get_bar_frominvesting(code, prev=120, interval=3600): if interval == "day": interval = 86400 elif interval == "hour": interval = 3600 elif interval == "minute": interval = 60 elif interval == 86400 * 7: interval = "week" elif interval == 86400 * 30: interval = "month" if len(code.split("/")) == 2: code = get_investing_id(code) url = "https://cn.investing.com" headers = { "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)\ AppleWebKit/537.36 (KHTML, like Gecko)", "Host": "cn.investing.com", "Referer": "https://cn.investing.com/commodities/", "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-origin", "X-Requested-With": "XMLHttpRequest", } r = rget( url + "/common/modules/js_instrument_chart/api/data.php?pair_id={code}&pair_id_for_news={code}\ &chart_type=area&pair_interval={interval}&candle_count={prev}&events=yes&volume_series=yes&period=".format( code=code, prev=str(prev), interval=str(interval) ), headers=headers, ) if not r.text: return # None r = r.json() df = pd.DataFrame(r["candles"], columns=["date", "close", "0", "1"]) df = df.drop(["0", "1"], axis=1) df["date"] = df["date"].apply( lambda t: dt.datetime.fromtimestamp(t / 1000, tz=tz_bj).replace(tzinfo=None) ) return df def get_bar_fromxq(code, prev, interval=3600): # max interval is also around 500 trans = { "60": "1m", "300": "5m", "900": "15m", "1800": "30m", "3600": "60m", "7200": "120m", "86400": "day", "604800": "week", "2592000": "month", } code, type_ = decouple_code(code) interval = trans.get(str(interval), interval) url = "https://stock.xueqiu.com/v5/stock/chart/kline.json?symbol={code}&begin={tomorrow}&period={interval}&type={type_}\ &count=-{prev}&indicator=kline,pe,pb,ps,pcf,market_capital,agt,ggt,balance".format( code=code, tomorrow=int(tomorrow_ts() * 1000), prev=prev, interval=interval, type_=type_, ) r = rget( url, headers={"user-agent": "Mozilla/5.0"}, cookies={"xq_a_token": get_token()} ) if not r.text: return # None else: df = pd.DataFrame(r.json()["data"]["item"], columns=r.json()["data"]["column"]) df["date"] = df["timestamp"].apply( lambda t: dt.datetime.fromtimestamp(t / 1000, tz=tz_bj).replace(tzinfo=None) ) df = df[ [ "date", "open", "high", "low", "close", "volume", "turnoverrate", "percent", ] ] return df def get_bar_fromwsj(code, token=None, interval=3600): # proxy required # code = "FUTURE/US/XNYM/CLM20" # TODO: also not explore the code format here extensively trans = {"3600": "1H"} # TODO: there is other freq tags, but I have no time to explore them, contributions are welcome:) freq = trans.get(str(interval), interval) if not token: token = "cecc4267a0194af89ca343805a3e57af" # the thing I am concerned here is whether token is refreshed params = { "json": '{"Step":"PT%s","TimeFrame":"D5","EntitlementToken":"%s",\ "IncludeMockTick":true,"FilterNullSlots":false,"FilterClosedPoints":true,"IncludeClosedSlots":false,\ "IncludeOfficialClose":true,"InjectOpen":false,"ShowPreMarket":false,"ShowAfterHours":false,\ "UseExtendedTimeFrame":false,"WantPriorClose":true,"IncludeCurrentQuotes":false,\ "ResetTodaysAfterHoursPercentChange":false,\ "Series":[{"Key":"%s","Dialect":"Charting","Kind":"Ticker","SeriesId":"s1","DataTypes":["Last"]}]}' % (freq, token, code), "ckey": token[:10], } r = rget_json( "https://api-secure.wsj.net/api/michelangelo/timeseries/history", params=params, headers={ "user-agent": "Mozilla/5.0", "Accept": "application/json, text/javascript, */*; q=0.01", "Dylan2010.EntitlementToken": token, "Host": "api-secure.wsj.net", "Origin": "https://www.marketwatch.com", "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "cross-site", }, ) df = pd.DataFrame( { "date": r["TimeInfo"]["Ticks"], "close": [n[0] for n in r["Series"][0]["DataPoints"]], } ) df["date"] = pd.to_datetime(df["date"] * 1000000) + pd.Timedelta(hours=8) df = df[df["close"] > -100.0] # 存在未来数据占位符需要排除 return df class vinfo(basicinfo, indicator): def __init__( self, code, name=None, start=None, end=None, rate=0, col="close", normalization=True, **kws ): if not name: try: name = get_rt(code)["name"] except: name = code self.name = name self.code = code self.start = start # None is one year ago self.end = end # None is yesterday df = get_daily(code, start=start, end=end) df[col] = pd.to_numeric(df[col]) # in case the col is not float df["totvalue"] = df[col] if normalization: df["netvalue"] = df[col] / df.iloc[0][col] else: df["netvalue"] = df[col] self.price = df self.round_label = kws.get("round_label", 0) self.dividend_label = kws.get("dividend_label", 0) self.value_label = kws.get("value_label", 1) # 默认按金额赎回 self.specialdate = [] self.fenhongdate = [] self.zhesuandate = [] self.rate = rate VInfo = vinfo
true
true
f7278b3f78adb6b6654bc60e19101d05927cea4c
1,039
py
Python
modules/denoise/config.py
gw2cc/godot
addaa48039fff0795b99cf998a11a75a9e280850
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
1
2022-02-26T05:16:25.000Z
2022-02-26T05:16:25.000Z
modules/denoise/config.py
gw2cc/godot
addaa48039fff0795b99cf998a11a75a9e280850
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
2
2021-12-10T04:07:19.000Z
2021-12-27T20:00:03.000Z
modules/denoise/config.py
gw2cc/godot
addaa48039fff0795b99cf998a11a75a9e280850
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
def can_build(env, platform): # Thirdparty dependency OpenImage Denoise includes oneDNN library # and the version we use only supports x86_64. # It's also only relevant for tools build and desktop platforms, # as doing lightmap generation and denoising on Android or HTML5 # would be a bit far-fetched. # Note: oneDNN doesn't support ARM64, OIDN needs updating to the latest version supported_platform = platform in ["x11", "osx", "windows", "server"] supported_bits = env["bits"] == "64" supported_arch = env["arch"] != "arm64" and not env["arch"].startswith("rv") # Hack to disable on Linux arm64. This won't work well for cross-compilation (checks # host, not target) and would need a more thorough fix by refactoring our arch and # bits-handling code. from platform import machine if platform == "x11" and machine() != "x86_64": supported_arch = False return env["tools"] and supported_platform and supported_bits and supported_arch def configure(env): pass
41.56
88
0.704524
def can_build(env, platform): # as doing lightmap generation and denoising on Android or HTML5 # would be a bit far-fetched. # Note: oneDNN doesn't support ARM64, OIDN needs updating to the latest version supported_platform = platform in ["x11", "osx", "windows", "server"] supported_bits = env["bits"] == "64" supported_arch = env["arch"] != "arm64" and not env["arch"].startswith("rv") # host, not target) and would need a more thorough fix by refactoring our arch and # bits-handling code. from platform import machine if platform == "x11" and machine() != "x86_64": supported_arch = False return env["tools"] and supported_platform and supported_bits and supported_arch def configure(env): pass
true
true
f7278bb2aaab500d948340fdddc1c5f836645f0b
97,520
py
Python
wordlist.py
Finoozer/pypassgen
37a129f0917871f8ea6680e7820a110df779f5f2
[ "MIT" ]
null
null
null
wordlist.py
Finoozer/pypassgen
37a129f0917871f8ea6680e7820a110df779f5f2
[ "MIT" ]
null
null
null
wordlist.py
Finoozer/pypassgen
37a129f0917871f8ea6680e7820a110df779f5f2
[ "MIT" ]
null
null
null
wl = ["aah", "aaron", "aba", "ababa", "aback", "abase", "abash", "abate", "abbas", "abbe", "abbey", "abbot", "abbott", "abc", "abe", "abed", "abel", "abet", "abide", "abject", "ablaze", "able", "abner", "abo", "abode", "abort", "about", "above", "abrade", "abram", "absorb", "abuse", "abut", "abyss", "acadia", "accra", "accrue", "ace", "acetic", "ache", "acid", "acidic", "acm", "acme", "acorn", "acre", "acrid", "act", "acton", "actor", "acts", "acuity", "acute", "ada", "adage", "adagio", "adair", "adam", "adams", "adapt", "add", "added", "addict", "addis", "addle", "adele", "aden", "adept", "adieu", "adjust", "adler", "admit", "admix", "ado", "adobe", "adonis", "adopt", "adore", "adorn", "adult", "advent", "advert", "advise", "aegis", "aeneid", "afar", "affair", "affine", "affix", "afire", "afoot", "afraid", "africa", "afro", "aft", "again", "agate", "agave", "age", "age", "agenda", "agent", "agile", "aging", "agnes", "agnew", "ago", "agone", "agony", "agree", "ague", "agway", "ahead", "ahem", "ahoy", "aid", "aida", "aide", "aides", "aiken", "ail", "aile", "aim", "ainu", "air", "aires", "airman", "airway", "airy", "aisle", "ajar", "ajax", "akers", "akin", "akron", "ala", "alai", "alamo", "alan", "alarm", "alaska", "alb", "alba", "album", "alcoa", "alden", "alder", "ale", "alec", "aleck", "aleph", "alert", "alex", "alexei", "alga", "algae", "algal", "alger", "algol", "ali", "alia", "alias", "alibi", "alice", "alien", "alight", "align", "alike", "alive", "all", "allah", "allan", "allay", "allen", "alley", "allied", "allis", "allot", "allow", "alloy", "allure", "ally", "allyl", "allyn", "alma", "almost", "aloe", "aloft", "aloha", "alone", "along", "aloof", "aloud", "alp", "alpha", "alps", "also", "alsop", "altair", "altar", "alter", "alto", "alton", "alum", "alumni", "alva", "alvin", "alway", "ama", "amass", "amaze", "amber", "amble", "ambush", "amen", "amend", "ames", "ami", "amid", "amide", "amigo", "amino", "amiss", "amity", "amman", "ammo", "amoco", "amok", "among", "amort", "amos", "amp", "ampere", "ampex", "ample", "amply", "amra", "amulet", "amuse", "amy", "ana", "and", "andes", "andre", "andrew", "andy", "anent", "anew", "angel", "angelo", "anger", "angie", "angle", "anglo", "angola", "angry", "angst", "angus", "ani", "anion", "anise", "anita", "ankle", "ann", "anna", "annal", "anne", "annex", "annie", "annoy", "annul", "annuli", "annum", "anode", "ansi", "answer", "ant", "ante", "anti", "antic", "anton", "anus", "anvil", "any", "anyhow", "anyway", "aok", "aorta", "apart", "apathy", "ape", "apex", "aphid", "aplomb", "appeal", "append", "apple", "apply", "april", "apron", "apse", "apt", "aqua", "arab", "araby", "arc", "arcana", "arch", "archer", "arden", "ardent", "are", "area", "arena", "ares", "argive", "argo", "argon", "argot", "argue", "argus", "arhat", "arid", "aries", "arise", "ark", "arlen", "arlene", "arm", "armco", "army", "arnold", "aroma", "arose", "arpa", "array", "arrear", "arrow", "arson", "art", "artery", "arthur", "artie", "arty", "aruba", "arum", "aryl", "ascend", "ash", "ashen", "asher", "ashley", "ashy", "asia", "aside", "ask", "askew", "asleep", "aspen", "aspire", "ass", "assai", "assam", "assay", "asset", "assort", "assure", "aster", "astm", "astor", "astral", "ate", "athens", "atlas", "atom", "atomic", "atone", "atop", "attic", "attire", "aubrey", "audio", "audit", "aug", "auger", "augur", "august", "auk", "aunt", "aura", "aural", "auric", "austin", "auto", "autumn", "avail", "ave", "aver", "avert", "avery", "aviate", "avid", "avis", "aviv", "avoid", "avon", "avow", "await", "awake", "award", "aware", "awash", "away", "awe", "awful", "awl", "awn", "awoke", "awry", "axe", "axes", "axial", "axiom", "axis", "axle", "axon", "aye", "ayers", "aztec", "azure", "babe", "babel", "baby", "bach", "back", "backup", "bacon", "bad", "bade", "baden", "badge", "baffle", "bag", "baggy", "bah", "bahama", "bail", "baird", "bait", "bake", "baku", "bald", "baldy", "bale", "bali", "balk", "balkan", "balky", "ball", "balled", "ballot", "balm", "balmy", "balsa", "bam", "bambi", "ban", "banal", "band", "bandit", "bandy", "bane", "bang", "banish", "banjo", "bank", "banks", "bantu", "bar", "barb", "bard", "bare", "barfly", "barge", "bark", "barley", "barn", "barnes", "baron", "barony", "barr", "barre", "barry", "barter", "barth", "barton", "basal", "base", "basel", "bash", "basic", "basil", "basin", "basis", "bask", "bass", "bassi", "basso", "baste", "bat", "batch", "bate", "bater", "bates", "bath", "bathe", "batik", "baton", "bator", "batt", "bauble", "baud", "bauer", "bawd", "bawdy", "bawl", "baxter", "bay", "bayda", "bayed", "bayou", "bazaar", "bbb", "bbbb", "bcd", "beach", "bead", "beady", "beak", "beam", "bean", "bear", "beard", "beast", "beat", "beau", "beauty", "beaux", "bebop", "becalm", "beck", "becker", "becky", "bed", "bedim", "bee", "beebe", "beech", "beef", "beefy", "been", "beep", "beer", "beet", "befall", "befit", "befog", "beg", "began", "beget", "beggar", "begin", "begun", "behind", "beige", "being", "beirut", "bel", "bela", "belch", "belfry", "belie", "bell", "bella", "belle", "belly", "below", "belt", "bema", "beman", "bemoan", "ben", "bench", "bend", "bender", "benny", "bent", "benz", "berea", "bereft", "beret", "berg", "berlin", "bern", "berne", "bernet", "berra", "berry", "bert", "berth", "beryl", "beset", "bess", "bessel", "best", "bestir", "bet", "beta", "betel", "beth", "bethel", "betsy", "bette", "betty", "bevel", "bevy", "beware", "bey", "bezel", "bhoy", "bias", "bib", "bibb", "bible", "bicep", "biceps", "bid", "biddy", "bide", "bien", "big", "biggs", "bigot", "bile", "bilge", "bilk", "bill", "billow", "billy", "bin", "binary", "bind", "bing", "binge", "bingle", "bini", "biota", "birch", "bird", "birdie", "birth", "bison", "bisque", "bit", "bitch", "bite", "bitt", "bitten", "biz", "bizet", "blab", "black", "blade", "blair", "blake", "blame", "blanc", "bland", "blank", "blare", "blast", "blat", "blatz", "blaze", "bleak", "bleat", "bled", "bleed", "blend", "bless", "blest", "blew", "blimp", "blind", "blink", "blinn", "blip", "bliss", "blithe", "blitz", "bloat", "blob", "bloc", "bloch", "block", "bloke", "blond", "blonde", "blood", "bloom", "bloop", "blot", "blotch", "blow", "blown", "blue", "bluet", "bluff", "blum", "blunt", "blur", "blurt", "blush", "blvd", "blythe", "bmw", "boa", "boar", "board", "boast", "boat", "bob", "bobbin", "bobby", "bobcat", "boca", "bock", "bode", "body", "bog", "bogey", "boggy", "bogus", "bogy", "bohr", "boil", "bois", "boise", "bold", "bole", "bolo", "bolt", "bomb", "bombay", "bon", "bona", "bond", "bone", "bong", "bongo", "bonn", "bonus", "bony", "bonze", "boo", "booby", "boogie", "book", "booky", "boom", "boon", "boone", "boor", "boost", "boot", "booth", "booty", "booze", "bop", "borax", "border", "bore", "borg", "boric", "boris", "born", "borne", "borneo", "boron", "bosch", "bose", "bosom", "boson", "boss", "boston", "botch", "both", "bottle", "bough", "bouncy", "bound", "bourn", "bout", "bovine", "bow", "bowel", "bowen", "bowie", "bowl", "box", "boxy", "boy", "boyar", "boyce", "boyd", "boyle", "brace", "bract", "brad", "brady", "brae", "brag", "bragg", "braid", "brain", "brainy", "brake", "bran", "brand", "brandt", "brant", "brash", "brass", "brassy", "braun", "brave", "bravo", "brawl", "bray", "bread", "break", "bream", "breath", "bred", "breed", "breeze", "bremen", "brent", "brest", "brett", "breve", "brew", "brian", "briar", "bribe", "brice", "brick", "bride", "brief", "brig", "briggs", "brim", "brine", "bring", "brink", "briny", "brisk", "broad", "brock", "broil", "broke", "broken", "bronx", "brood", "brook", "brooke", "broom", "broth", "brow", "brown", "browse", "bruce", "bruit", "brunch", "bruno", "brunt", "brush", "brute", "bryan", "bryant", "bryce", "bryn", "bstj", "btl", "bub", "buck", "bud", "budd", "buddy", "budge", "buena", "buenos", "buff", "bug", "buggy", "bugle", "buick", "build", "built", "bulb", "bulge", "bulk", "bulky", "bull", "bully", "bum", "bump", "bun", "bunch", "bundy", "bunk", "bunny", "bunt", "bunyan", "buoy", "burch", "bureau", "buret", "burg", "buried", "burke", "burl", "burly", "burma", "burn", "burnt", "burp", "burr", "burro", "burst", "burt", "burton", "burtt", "bury", "bus", "busch", "bush", "bushel", "bushy", "buss", "bust", "busy", "but", "butane", "butch", "buteo", "butt", "butte", "butyl", "buxom", "buy", "buyer", "buzz", "buzzy", "bye", "byers", "bylaw", "byline", "byrd", "byrne", "byron", "byte", "byway", "byword", "cab", "cabal", "cabin", "cable", "cabot", "cacao", "cache", "cacm", "cacti", "caddy", "cadent", "cadet", "cadre", "cady", "cafe", "cage", "cagey", "cahill", "caiman", "cain", "caine", "cairn", "cairo", "cake", "cal", "calder", "caleb", "calf", "call", "calla", "callus", "calm", "calve", "cam", "camber", "came", "camel", "cameo", "camp", "can", "canal", "canary", "cancer", "candle", "candy", "cane", "canis", "canna", "cannot", "canny", "canoe", "canon", "canopy", "cant", "canto", "canton", "cap", "cape", "caper", "capo", "car", "carbon", "card", "care", "caress", "caret", "carey", "cargo", "carib", "carl", "carla", "carlo", "carne", "carob", "carol", "carp", "carpet", "carr", "carrie", "carry", "carson", "cart", "carte", "caruso", "carve", "case", "casey", "cash", "cashew", "cask", "casket", "cast", "caste", "cat", "catch", "cater", "cathy", "catkin", "catsup", "cauchy", "caulk", "cause", "cave", "cavern", "cavil", "cavort", "caw", "cayuga", "cbs", "ccc", "cccc", "cdc", "cease", "cecil", "cedar", "cede", "ceil", "celia", "cell", "census", "cent", "ceres", "cern", "cetera", "cetus", "chad", "chafe", "chaff", "chai", "chain", "chair", "chalk", "champ", "chance", "chang", "chant", "chao", "chaos", "chap", "chapel", "char", "chard", "charm", "chart", "chase", "chasm", "chaste", "chat", "chaw", "cheap", "cheat", "check", "cheek", "cheeky", "cheer", "chef", "chen", "chert", "cherub", "chess", "chest", "chevy", "chew", "chi", "chic", "chick", "chide", "chief", "child", "chile", "chili", "chill", "chilly", "chime", "chin", "china", "chine", "chink", "chip", "chirp", "chisel", "chit", "chive", "chock", "choir", "choke", "chomp", "chop", "chopin", "choral", "chord", "chore", "chose", "chosen", "chou", "chow", "chris", "chub", "chuck", "chuff", "chug", "chum", "chump", "chunk", "churn", "chute", "cia", "cicada", "cider", "cigar", "cilia", "cinch", "cindy", "cipher", "circa", "circe", "cite", "citrus", "city", "civet", "civic", "civil", "clad", "claim", "clam", "clammy", "clamp", "clan", "clang", "clank", "clap", "clara", "clare", "clark", "clarke", "clash", "clasp", "class", "claus", "clause", "claw", "clay", "clean", "clear", "cleat", "cleft", "clerk", "cliche", "click", "cliff", "climb", "clime", "cling", "clink", "clint", "clio", "clip", "clive", "cloak", "clock", "clod", "clog", "clomp", "clone", "close", "closet", "clot", "cloth", "cloud", "clout", "clove", "clown", "cloy", "club", "cluck", "clue", "cluj", "clump", "clumsy", "clung", "clyde", "coach", "coal", "coast", "coat", "coax", "cobb", "cobble", "cobol", "cobra", "coca", "cock", "cockle", "cocky", "coco", "cocoa", "cod", "coda", "coddle", "code", "codon", "cody", "coed", "cog", "cogent", "cohen", "cohn", "coil", "coin", "coke", "col", "cola", "colby", "cold", "cole", "colon", "colony", "colt", "colza", "coma", "comb", "combat", "come", "comet", "cometh", "comic", "comma", "con", "conch", "cone", "coney", "congo", "conic", "conn", "conner", "conway", "cony", "coo", "cook", "cooke", "cooky", "cool", "cooley", "coon", "coop", "coors", "coot", "cop", "cope", "copra", "copy", "coral", "corbel", "cord", "core", "corey", "cork", "corn", "corny", "corp", "corps", "corvus", "cos", "cosec", "coset", "cosh", "cost", "costa", "cosy", "cot", "cotta", "cotty", "couch", "cough", "could", "count", "coup", "coupe", "court", "cousin", "cove", "coven", "cover", "covet", "cow", "cowan", "cowl", "cowman", "cowry", "cox", "coy", "coyote", "coypu", "cozen", "cozy", "cpa", "crab", "crack", "craft", "crag", "craig", "cram", "cramp", "crane", "crank", "crap", "crash", "crass", "crate", "crater", "crave", "craw", "crawl", "craze", "crazy", "creak", "cream", "credit", "credo", "creed", "creek", "creep", "creole", "creon", "crepe", "crept", "cress", "crest", "crete", "crew", "crib", "cried", "crime", "crimp", "crisp", "criss", "croak", "crock", "crocus", "croft", "croix", "crone", "crony", "crook", "croon", "crop", "cross", "crow", "crowd", "crown", "crt", "crud", "crude", "cruel", "crumb", "crump", "crush", "crust", "crux", "cruz", "cry", "crypt", "cub", "cuba", "cube", "cubic", "cud", "cuddle", "cue", "cuff", "cull", "culpa", "cult", "cumin", "cuny", "cup", "cupful", "cupid", "cur", "curb", "curd", "cure", "curfew", "curia", "curie", "curio", "curl", "curry", "curse", "curt", "curve", "cusp", "cut", "cute", "cutlet", "cycad", "cycle", "cynic", "cyril", "cyrus", "cyst", "czar", "czech", "dab", "dacca", "dactyl", "dad", "dada", "daddy", "dade", "daffy", "dahl", "dahlia", "dairy", "dais", "daisy", "dakar", "dale", "daley", "dally", "daly", "dam", "dame", "damn", "damon", "damp", "damsel", "dan", "dana", "dance", "dandy", "dane", "dang", "dank", "danny", "dante", "dar", "dare", "dark", "darken", "darn", "darry", "dart", "dash", "data", "date", "dater", "datum", "daub", "daunt", "dave", "david", "davis", "davit", "davy", "dawn", "dawson", "day", "daze", "ddd", "dddd", "deacon", "dead", "deaf", "deal", "dealt", "dean", "deane", "dear", "death", "debar", "debby", "debit", "debra", "debris", "debt", "debug", "debut", "dec", "decal", "decay", "decca", "deck", "decker", "decor", "decree", "decry", "dee", "deed", "deem", "deep", "deer", "deere", "def", "defer", "deform", "deft", "defy", "degas", "degum", "deify", "deign", "deity", "deja", "del", "delay", "delft", "delhi", "delia", "dell", "della", "delta", "delve", "demark", "demit", "demon", "demur", "den", "deneb", "denial", "denny", "dense", "dent", "denton", "deny", "depot", "depth", "depute", "derby", "derek", "des", "desist", "desk", "detach", "deter", "deuce", "deus", "devil", "devoid", "devon", "dew", "dewar", "dewey", "dewy", "dey", "dhabi", "dial", "diana", "diane", "diary", "dibble", "dice", "dick", "dicta", "did", "dido", "die", "died", "diego", "diem", "diesel", "diet", "diety", "dietz", "dig", "digit", "dilate", "dill", "dim", "dime", "din", "dinah", "dine", "ding", "dingo", "dingy", "dint", "diode", "dip", "dirac", "dire", "dirge", "dirt", "dirty", "dis", "disc", "dish", "disk", "disney", "ditch", "ditto", "ditty", "diva", "divan", "dive", "dixie", "dixon", "dizzy", "dna", "dobbs", "dobson", "dock", "docket", "dod", "dodd", "dodge", "dodo", "doe", "doff", "dog", "doge", "dogma", "dolan", "dolce", "dole", "doll", "dolly", "dolt", "dome", "don", "done", "doneck", "donna", "donor", "doom", "door", "dope", "dora", "doria", "doric", "doris", "dose", "dot", "dote", "double", "doubt", "douce", "doug", "dough", "dour", "douse", "dove", "dow", "dowel", "down", "downs", "dowry", "doyle", "doze", "dozen", "drab", "draco", "draft", "drag", "drain", "drake", "dram", "drama", "drank", "drape", "draw", "drawl", "drawn", "dread", "dream", "dreamy", "dreg", "dress", "dressy", "drew", "drib", "dried", "drier", "drift", "drill", "drink", "drip", "drive", "droll", "drone", "drool", "droop", "drop", "dross", "drove", "drown", "drub", "drug", "druid", "drum", "drunk", "drury", "dry", "dryad", "dual", "duane", "dub", "dubhe", "dublin", "ducat", "duck", "duct", "dud", "due", "duel", "duet", "duff", "duffy", "dug", "dugan", "duke", "dull", "dully", "dulse", "duly", "duma", "dumb", "dummy", "dump", "dumpy", "dun", "dunce", "dune", "dung", "dunham", "dunk", "dunlop", "dunn", "dupe", "durer", "dusk", "dusky", "dust", "dusty", "dutch", "duty", "dwarf", "dwell", "dwelt", "dwight", "dwyer", "dyad", "dye", "dyer", "dying", "dyke", "dylan", "dyne", "each", "eagan", "eager", "eagle", "ear", "earl", "earn", "earth", "ease", "easel", "east", "easy", "eat", "eaten", "eater", "eaton", "eave", "ebb", "eben", "ebony", "echo", "eclat", "ecole", "eddie", "eddy", "eden", "edgar", "edge", "edgy", "edict", "edify", "edit", "edith", "editor", "edna", "edt", "edwin", "eee", "eeee", "eel", "eeoc", "eerie", "efface", "effie", "efg", "eft", "egan", "egg", "ego", "egress", "egret", "egypt", "eider", "eight", "eire", "eject", "eke", "elan", "elate", "elba", "elbow", "elder", "eldon", "elect", "elegy", "elena", "eleven", "elfin", "elgin", "eli", "elide", "eliot", "elite", "elk", "ell", "ella", "ellen", "ellis", "elm", "elmer", "elope", "else", "elsie", "elton", "elude", "elute", "elves", "ely", "embalm", "embark", "embed", "ember", "emcee", "emery", "emil", "emile", "emily", "emit", "emma", "emory", "empty", "enact", "enamel", "end", "endow", "enemy", "eng", "engel", "engle", "engulf", "enid", "enjoy", "enmity", "enoch", "enol", "enos", "enrico", "ensue", "enter", "entrap", "entry", "envoy", "envy", "epa", "epic", "epoch", "epoxy", "epsom", "equal", "equip", "era", "erase", "erato", "erda", "ere", "erect", "erg", "eric", "erich", "erie", "erik", "ernest", "ernie", "ernst", "erode", "eros", "err", "errand", "errol", "error", "erupt", "ervin", "erwin", "essay", "essen", "essex", "est", "ester", "estes", "estop", "eta", "etc", "etch", "ethan", "ethel", "ether", "ethic", "ethos", "ethyl", "etude", "eucre", "euler", "eureka", "eva", "evade", "evans", "eve", "even", "event", "every", "evict", "evil", "evoke", "evolve", "ewe", "ewing", "exact", "exalt", "exam", "excel", "excess", "exert", "exile", "exist", "exit", "exodus", "expel", "extant", "extent", "extol", "extra", "exude", "exult", "exxon", "eye", "eyed", "ezra", "faa", "faber", "fable", "face", "facet", "facile", "fact", "facto", "fad", "fade", "faery", "fag", "fahey", "fail", "fain", "faint", "fair", "fairy", "faith", "fake", "fall", "false", "fame", "fan", "fancy", "fang", "fanny", "fanout", "far", "farad", "farce", "fare", "fargo", "farley", "farm", "faro", "fast", "fat", "fatal", "fate", "fatty", "fault", "faun", "fauna", "faust", "fawn", "fay", "faze", "fbi", "fcc", "fda", "fear", "feast", "feat", "feb", "fed", "fee", "feed", "feel", "feet", "feign", "feint", "felice", "felix", "fell", "felon", "felt", "femur", "fence", "fend", "fermi", "fern", "ferric", "ferry", "fest", "fetal", "fetch", "fete", "fetid", "fetus", "feud", "fever", "few", "fff", "ffff", "fgh", "fiat", "fib", "fibrin", "fiche", "fide", "fief", "field", "fiend", "fiery", "fife", "fifo", "fifth", "fifty", "fig", "fight", "filch", "file", "filet", "fill", "filler", "filly", "film", "filmy", "filth", "fin", "final", "finale", "finch", "find", "fine", "finite", "fink", "finn", "finny", "fir", "fire", "firm", "first", "fish", "fishy", "fisk", "fiske", "fist", "fit", "fitch", "five", "fix", "fjord", "flack", "flag", "flail", "flair", "flak", "flake", "flaky", "flam", "flame", "flank", "flap", "flare", "flash", "flask", "flat", "flatus", "flaw", "flax", "flea", "fleck", "fled", "flee", "fleet", "flesh", "flew", "flex", "flick", "flier", "flinch", "fling", "flint", "flip", "flirt", "flit", "flo", "float", "floc", "flock", "floe", "flog", "flood", "floor", "flop", "floppy", "flora", "flour", "flout", "flow", "flown", "floyd", "flu", "flub", "flue", "fluff", "fluid", "fluke", "flung", "flush", "flute", "flux", "fly", "flyer", "flynn", "fmc", "foal", "foam", "foamy", "fob", "focal", "foci", "focus", "fodder", "foe", "fog", "foggy", "fogy", "foil", "foist", "fold", "foley", "folio", "folk", "folly", "fond", "font", "food", "fool", "foot", "foote", "fop", "for", "foray", "force", "ford", "fore", "forge", "forgot", "fork", "form", "fort", "forte", "forth", "forty", "forum", "foss", "fossil", "foul", "found", "fount", "four", "fovea", "fowl", "fox", "foxy", "foyer", "fpc", "frail", "frame", "fran", "franc", "franca", "frank", "franz", "frau", "fraud", "fray", "freak", "fred", "free", "freed", "freer", "frenzy", "freon", "fresh", "fret", "freud", "frey", "freya", "friar", "frick", "fried", "frill", "frilly", "frisky", "fritz", "fro", "frock", "frog", "from", "front", "frost", "froth", "frown", "froze", "fruit", "fry", "frye", "ftc", "fuchs", "fudge", "fuel", "fugal", "fugue", "fuji", "full", "fully", "fum", "fume", "fun", "fund", "fungal", "fungi", "funk", "funny", "fur", "furl", "furry", "fury", "furze", "fuse", "fuss", "fussy", "fusty", "fuzz", "fuzzy", "gab", "gable", "gabon", "gad", "gadget", "gaff", "gaffe", "gag", "gage", "gail", "gain", "gait", "gal", "gala", "galaxy", "gale", "galen", "gall", "gallop", "galt", "gam", "game", "gamin", "gamma", "gamut", "gander", "gang", "gao", "gap", "gape", "gar", "garb", "garish", "garner", "garry", "garth", "gary", "gas", "gash", "gasp", "gassy", "gate", "gates", "gator", "gauche", "gaudy", "gauge", "gaul", "gaunt", "gaur", "gauss", "gauze", "gave", "gavel", "gavin", "gawk", "gawky", "gay", "gaze", "gear", "gecko", "gee", "geese", "geigy", "gel", "geld", "gem", "gemma", "gene", "genie", "genii", "genoa", "genre", "gent", "gentry", "genus", "gerbil", "germ", "gerry", "get", "getty", "ggg", "gggg", "ghana", "ghent", "ghetto", "ghi", "ghost", "ghoul", "giant", "gibbs", "gibby", "gibe", "giddy", "gift", "gig", "gil", "gila", "gild", "giles", "gill", "gilt", "gimbal", "gimpy", "gin", "gina", "ginn", "gino", "gird", "girl", "girth", "gist", "give", "given", "glad", "gladdy", "glade", "glamor", "gland", "glans", "glare", "glass", "glaze", "gleam", "glean", "glee", "glen", "glenn", "glib", "glide", "glint", "gloat", "glob", "globe", "glom", "gloom", "glory", "gloss", "glove", "glow", "glue", "glued", "gluey", "gluing", "glum", "glut", "glyph", "gmt", "gnarl", "gnash", "gnat", "gnaw", "gnome", "gnp", "gnu", "goa", "goad", "goal", "goat", "gob", "goer", "goes", "goff", "gog", "goggle", "gogh", "gogo", "gold", "golf", "golly", "gone", "gong", "goo", "good", "goode", "goody", "goof", "goofy", "goose", "gop", "gordon", "gore", "goren", "gorge", "gorky", "gorse", "gory", "gosh", "gospel", "got", "gouda", "gouge", "gould", "gourd", "gout", "gown", "gpo", "grab", "grace", "grad", "grade", "grady", "graff", "graft", "grail", "grain", "grand", "grant", "grape", "graph", "grasp", "grass", "grata", "grate", "grater", "grave", "gravy", "gray", "graze", "great", "grebe", "greed", "greedy", "greek", "green", "greer", "greet", "greg", "gregg", "greta", "grew", "grey", "grid", "grief", "grieve", "grill", "grim", "grime", "grimm", "grin", "grind", "grip", "gripe", "grist", "grit", "groan", "groat", "groin", "groom", "grope", "gross", "groton", "group", "grout", "grove", "grow", "growl", "grown", "grub", "gruff", "grunt", "gsa", "guam", "guano", "guard", "guess", "guest", "guide", "guild", "guile", "guilt", "guise", "guitar", "gules", "gulf", "gull", "gully", "gulp", "gum", "gumbo", "gummy", "gun", "gunk", "gunky", "gunny", "gurgle", "guru", "gus", "gush", "gust", "gusto", "gusty", "gut", "gutsy", "guy", "guyana", "gwen", "gwyn", "gym", "gyp", "gypsy", "gyro", "haag", "haas", "habib", "habit", "hack", "had", "hades", "hadron", "hagen", "hager", "hague", "hahn", "haifa", "haiku", "hail", "hair", "hairy", "haiti", "hal", "hale", "haley", "half", "hall", "halma", "halo", "halt", "halvah", "halve", "ham", "hamal", "hamlin", "han", "hand", "handy", "haney", "hang", "hank", "hanna", "hanoi", "hans", "hansel", "hap", "happy", "hard", "hardy", "hare", "harem", "hark", "harley", "harm", "harp", "harpy", "harry", "harsh", "hart", "harvey", "hash", "hasp", "hast", "haste", "hasty", "hat", "hatch", "hate", "hater", "hath", "hatred", "haul", "haunt", "have", "haven", "havoc", "haw", "hawk", "hay", "haydn", "hayes", "hays", "hazard", "haze", "hazel", "hazy", "head", "heady", "heal", "healy", "heap", "hear", "heard", "heart", "heat", "heath", "heave", "heavy", "hebe", "hebrew", "heck", "heckle", "hedge", "heed", "heel", "heft", "hefty", "heigh", "heine", "heinz", "heir", "held", "helen", "helga", "helix", "hell", "hello", "helm", "helmut", "help", "hem", "hemp", "hen", "hence", "henri", "henry", "her", "hera", "herb", "herd", "here", "hero", "heroic", "heron", "herr", "hertz", "hess", "hesse", "hettie", "hetty", "hew", "hewitt", "hewn", "hex", "hey", "hhh", "hhhh", "hiatt", "hick", "hicks", "hid", "hide", "high", "hij", "hike", "hill", "hilly", "hilt", "hilum", "him", "hind", "hindu", "hines", "hinge", "hint", "hip", "hippo", "hippy", "hiram", "hire", "hirsch", "his", "hiss", "hit", "hitch", "hive", "hoagy", "hoar", "hoard", "hob", "hobbs", "hobby", "hobo", "hoc", "hock", "hodge", "hodges", "hoe", "hoff", "hog", "hogan", "hoi", "hokan", "hold", "holdup", "hole", "holly", "holm", "holst", "holt", "home", "homo", "honda", "hondo", "hone", "honey", "hong", "honk", "hooch", "hood", "hoof", "hook", "hookup", "hoop", "hoot", "hop", "hope", "horde", "horn", "horny", "horse", "horus", "hose", "host", "hot", "hotbox", "hotel", "hough", "hound", "hour", "house", "hove", "hovel", "hover", "how", "howdy", "howe", "howl", "hoy", "hoyt", "hub", "hubbub", "hubby", "huber", "huck", "hue", "hued", "huff", "hug", "huge", "hugh", "hughes", "hugo", "huh", "hulk", "hull", "hum", "human", "humid", "hump", "humus", "hun", "hunch", "hung", "hunk", "hunt", "hurd", "hurl", "huron", "hurrah", "hurry", "hurst", "hurt", "hurty", "hush", "husky", "hut", "hutch", "hyde", "hydra", "hydro", "hyena", "hying", "hyman", "hymen", "hymn", "hymnal", "iambic", "ian", "ibex", "ibid", "ibis", "ibm", "ibn", "icc", "ice", "icing", "icky", "icon", "icy", "ida", "idaho", "idea", "ideal", "idiom", "idiot", "idle", "idol", "idyll", "ieee", "iffy", "ifni", "igloo", "igor", "iii", "iiii", "ijk", "ike", "ileum", "iliac", "iliad", "ill", "illume", "ilona", "image", "imbue", "imp", "impel", "import", "impute", "inane", "inapt", "inc", "inca", "incest", "inch", "incur", "index", "india", "indies", "indy", "inept", "inert", "infect", "infer", "infima", "infix", "infra", "ingot", "inhere", "injun", "ink", "inlay", "inlet", "inman", "inn", "inner", "input", "insect", "inset", "insult", "intend", "inter", "into", "inure", "invoke", "ion", "ionic", "iota", "iowa", "ipso", "ira", "iran", "iraq", "irate", "ire", "irene", "iris", "irish", "irk", "irma", "iron", "irony", "irs", "irvin", "irwin", "isaac", "isabel", "ising", "isis", "islam", "island", "isle", "israel", "issue", "italy", "itch", "item", "ito", "itt", "ivan", "ive", "ivory", "ivy", "jab", "jack", "jacky", "jacm", "jacob", "jacobi", "jade", "jag", "jail", "jaime", "jake", "jam", "james", "jan", "jane", "janet", "janos", "janus", "japan", "jar", "jason", "java", "jaw", "jay", "jazz", "jazzy", "jean", "jed", "jeep", "jeff", "jejune", "jelly", "jenny", "jeres", "jerk", "jerky", "jerry", "jersey", "jess", "jesse", "jest", "jesus", "jet", "jew", "jewel", "jewett", "jewish", "jibe", "jiffy", "jig", "jill", "jilt", "jim", "jimmy", "jinx", "jive", "jjj", "jjjj", "jkl", "joan", "job", "jock", "jockey", "joe", "joel", "joey", "jog", "john", "johns", "join", "joint", "joke", "jolla", "jolly", "jolt", "jon", "jonas", "jones", "jorge", "jose", "josef", "joshua", "joss", "jostle", "jot", "joule", "joust", "jove", "jowl", "jowly", "joy", "joyce", "juan", "judas", "judd", "jude", "judge", "judo", "judy", "jug", "juggle", "juice", "juicy", "juju", "juke", "jukes", "julep", "jules", "julia", "julie", "julio", "july", "jumbo", "jump", "jumpy", "junco", "june", "junk", "junky", "juno", "junta", "jura", "jure", "juror", "jury", "just", "jut", "jute", "kabul", "kafka", "kahn", "kajar", "kale", "kalmia", "kane", "kant", "kapok", "kappa", "karate", "karen", "karl", "karma", "karol", "karp", "kate", "kathy", "katie", "katz", "kava", "kay", "kayo", "kazoo", "keats", "keel", "keen", "keep", "keg", "keith", "keller", "kelly", "kelp", "kemp", "ken", "keno", "kent", "kenya", "kepler", "kept", "kern", "kerr", "kerry", "ketch", "kevin", "key", "keyed", "keyes", "keys", "khaki", "khan", "khmer", "kick", "kid", "kidde", "kidney", "kiev", "kigali", "kill", "kim", "kin", "kind", "king", "kink", "kinky", "kiosk", "kiowa", "kirby", "kirk", "kirov", "kiss", "kit", "kite", "kitty", "kiva", "kivu", "kiwi", "kkk", "kkkk", "klan", "klaus", "klein", "kline", "klm", "klux", "knack", "knapp", "knauer", "knead", "knee", "kneel", "knelt", "knew", "knick", "knife", "knit", "knob", "knock", "knoll", "knot", "knott", "know", "known", "knox", "knurl", "koala", "koch", "kodak", "kola", "kombu", "kong", "koran", "korea", "kraft", "krause", "kraut", "krebs", "kruse", "kudo", "kudzu", "kuhn", "kulak", "kurd", "kurt", "kyle", "kyoto", "lab", "laban", "label", "labia", "labile", "lac", "lace", "lack", "lacy", "lad", "laden", "ladle", "lady", "lag", "lager", "lagoon", "lagos", "laid", "lain", "lair", "laity", "lake", "lam", "lamar", "lamb", "lame", "lamp", "lana", "lance", "land", "lane", "lang", "lange", "lanka", "lanky", "lao", "laos", "lap", "lapel", "lapse", "larch", "lard", "lares", "large", "lark", "larkin", "larry", "lars", "larva", "lase", "lash", "lass", "lasso", "last", "latch", "late", "later", "latest", "latex", "lath", "lathe", "latin", "latus", "laud", "laue", "laugh", "launch", "laura", "lava", "law", "lawn", "lawson", "lax", "lay", "layup", "laze", "lazy", "lea", "leach", "lead", "leaf", "leafy", "leak", "leaky", "lean", "leap", "leapt", "lear", "learn", "lease", "leash", "least", "leave", "led", "ledge", "lee", "leech", "leeds", "leek", "leer", "leery", "leeway", "left", "lefty", "leg", "legal", "leggy", "legion", "leigh", "leila", "leland", "lemma", "lemon", "len", "lena", "lend", "lenin", "lenny", "lens", "lent", "leo", "leon", "leona", "leone", "leper", "leroy", "less", "lessee", "lest", "let", "lethe", "lev", "levee", "level", "lever", "levi", "levin", "levis", "levy", "lew", "lewd", "lewis", "leyden", "liar", "libel", "libido", "libya", "lice", "lick", "lid", "lie", "lied", "lien", "lieu", "life", "lifo", "lift", "light", "like", "liken", "lila", "lilac", "lilly", "lilt", "lily", "lima", "limb", "limbo", "lime", "limit", "limp", "lin", "lind", "linda", "linden", "line", "linen", "lingo", "link", "lint", "linus", "lion", "lip", "lipid", "lisa", "lise", "lisle", "lisp", "list", "listen", "lit", "lithe", "litton", "live", "liven", "livid", "livre", "liz", "lizzie", "lll", "llll", "lloyd", "lmn", "load", "loaf", "loam", "loamy", "loan", "loath", "lob", "lobar", "lobby", "lobe", "lobo", "local", "loci", "lock", "locke", "locus", "lodge", "loeb", "loess", "loft", "lofty", "log", "logan", "loge", "logic", "loin", "loire", "lois", "loiter", "loki", "lola", "loll", "lolly", "lomb", "lome", "lone", "long", "look", "loom", "loon", "loop", "loose", "loot", "lop", "lope", "lopez", "lord", "lore", "loren", "los", "lose", "loss", "lossy", "lost", "lot", "lotte", "lotus", "lou", "loud", "louis", "louise", "louse", "lousy", "louver", "love", "low", "lowe", "lower", "lowry", "loy", "loyal", "lsi", "ltv", "lucas", "lucia", "lucid", "luck", "lucky", "lucre", "lucy", "lug", "luge", "luger", "luis", "luke", "lull", "lulu", "lumbar", "lumen", "lump", "lumpy", "lunar", "lunch", "lund", "lung", "lunge", "lura", "lurch", "lure", "lurid", "lurk", "lush", "lust", "lusty", "lute", "lutz", "lux", "luxe", "luzon", "lydia", "lye", "lying", "lykes", "lyle", "lyman", "lymph", "lynch", "lynn", "lynx", "lyon", "lyons", "lyra", "lyric", "mabel", "mac", "mace", "mach", "macho", "mack", "mackey", "macon", "macro", "mad", "madam", "made", "madman", "madsen", "mae", "magi", "magic", "magma", "magna", "magog", "maid", "maier", "mail", "maim", "main", "maine", "major", "make", "malady", "malay", "male", "mali", "mall", "malt", "malta", "mambo", "mamma", "mammal", "man", "mana", "manama", "mane", "mange", "mania", "manic", "mann", "manna", "manor", "mans", "manse", "mantle", "many", "mao", "maori", "map", "maple", "mar", "marc", "march", "marco", "marcy", "mardi", "mare", "margo", "maria", "marie", "marin", "marine", "mario", "mark", "marks", "marlin", "marrow", "marry", "mars", "marsh", "mart", "marty", "marx", "mary", "maser", "mash", "mask", "mason", "masque", "mass", "mast", "mat", "match", "mate", "mateo", "mater", "math", "matte", "maul", "mauve", "mavis", "maw", "mawr", "max", "maxim", "maxima", "may", "maya", "maybe", "mayer", "mayhem", "mayo", "mayor", "mayst", "mazda", "maze", "mba", "mccoy", "mcgee", "mckay", "mckee", "mcleod", "mead", "meal", "mealy", "mean", "meant", "meat", "meaty", "mecca", "mecum", "medal", "medea", "media", "medic", "medley", "meek", "meet", "meg", "mega", "meier", "meir", "mel", "meld", "melee", "mellow", "melon", "melt", "memo", "memoir", "men", "mend", "menlo", "menu", "merck", "mercy", "mere", "merge", "merit", "merle", "merry", "mesa", "mescal", "mesh", "meson", "mess", "messy", "met", "metal", "mete", "meter", "metro", "mew", "meyer", "meyers", "mezzo", "miami", "mica", "mice", "mickey", "micky", "micro", "mid", "midas", "midge", "midst", "mien", "miff", "mig", "might", "mike", "mila", "milan", "milch", "mild", "mildew", "mile", "miles", "milk", "milky", "mill", "mills", "milt", "mimi", "mimic", "mince", "mind", "mine", "mini", "minim", "mink", "minnow", "minor", "minos", "minot", "minsk", "mint", "minus", "mira", "mirage", "mire", "mirth", "miser", "misery", "miss", "missy", "mist", "misty", "mit", "mite", "mitre", "mitt", "mix", "mixup", "mizar", "mmm", "mmmm", "mno", "moan", "moat", "mob", "mobil", "mock", "modal", "mode", "model", "modem", "modish", "moe", "moen", "mohr", "moire", "moist", "molal", "molar", "mold", "mole", "moll", "mollie", "molly", "molt", "molten", "mommy", "mona", "monad", "mondo", "monel", "money", "monic", "monk", "mont", "monte", "month", "monty", "moo", "mood", "moody", "moon", "moor", "moore", "moose", "moot", "mop", "moral", "morale", "moran", "more", "morel", "morn", "moron", "morse", "morsel", "mort", "mosaic", "moser", "moses", "moss", "mossy", "most", "mot", "motel", "motet", "moth", "mother", "motif", "motor", "motto", "mould", "mound", "mount", "mourn", "mouse", "mousy", "mouth", "move", "movie", "mow", "moyer", "mph", "mrs", "much", "muck", "mucus", "mud", "mudd", "muddy", "muff", "muffin", "mug", "muggy", "mugho", "muir", "mulch", "mulct", "mule", "mull", "multi", "mum", "mummy", "munch", "mung", "munson", "muon", "muong", "mural", "muriel", "murk", "murky", "murre", "muse", "mush", "mushy", "music", "musk", "muslim", "must", "musty", "mute", "mutt", "muzak", "muzo", "myel", "myers", "mylar", "mynah", "myopia", "myra", "myron", "myrrh", "myself", "myth", "naacp", "nab", "nadir", "nag", "nagoya", "nagy", "naiad", "nail", "nair", "naive", "naked", "name", "nan", "nancy", "naomi", "nap", "nary", "nasa", "nasal", "nash", "nasty", "nat", "natal", "nate", "nato", "natty", "nature", "naval", "nave", "navel", "navy", "nay", "nazi", "nbc", "nbs", "ncaa", "ncr", "neal", "near", "neat", "neath", "neck", "ned", "nee", "need", "needy", "neff", "negate", "negro", "nehru", "neil", "nell", "nelsen", "neon", "nepal", "nero", "nerve", "ness", "nest", "net", "neuron", "neva", "neve", "new", "newel", "newt", "next", "nib", "nibs", "nice", "nicety", "niche", "nick", "niece", "niger", "nigh", "night", "nih", "nikko", "nil", "nile", "nimbus", "nimh", "nina", "nine", "ninth", "niobe", "nip", "nit", "nitric", "nitty", "nixon", "nnn", "nnnn", "noaa", "noah", "nob", "nobel", "noble", "nod", "nodal", "node", "noel", "noise", "noisy", "nolan", "noll", "nolo", "nomad", "non", "nonce", "none", "nook", "noon", "noose", "nop", "nor", "nora", "norm", "norma", "north", "norway", "nose", "not", "notch", "note", "notre", "noun", "nov", "nova", "novak", "novel", "novo", "now", "nrc", "nsf", "ntis", "nuance", "nubia", "nuclei", "nude", "nudge", "null", "numb", "nun", "nurse", "nut", "nyc", "nylon", "nymph", "nyu", "oaf", "oak", "oaken", "oakley", "oar", "oases", "oasis", "oat", "oath", "obese", "obey", "objet", "oboe", "occur", "ocean", "oct", "octal", "octave", "octet", "odd", "ode", "odin", "odium", "off", "offal", "offend", "offer", "oft", "often", "ogden", "ogle", "ogre", "ohio", "ohm", "ohmic", "oil", "oily", "oint", "okay", "olaf", "olav", "old", "olden", "oldy", "olga", "olin", "olive", "olsen", "olson", "omaha", "oman", "omega", "omen", "omit", "once", "one", "onion", "only", "onset", "onto", "onus", "onward", "onyx", "ooo", "oooo", "ooze", "opal", "opec", "opel", "open", "opera", "opium", "opt", "optic", "opus", "oral", "orate", "orb", "orbit", "orchid", "ordain", "order", "ore", "organ", "orgy", "orin", "orion", "ornery", "orono", "orr", "osaka", "oscar", "osier", "oslo", "other", "otis", "ott", "otter", "otto", "ouch", "ought", "ounce", "our", "oust", "out", "ouvre", "ouzel", "ouzo", "ova", "oval", "ovary", "ovate", "oven", "over", "overt", "ovid", "owe", "owens", "owing", "owl", "owly", "own", "oxen", "oxeye", "oxide", "oxnard", "ozark", "ozone", "pablo", "pabst", "pace", "pack", "packet", "pact", "pad", "paddy", "padre", "paean", "pagan", "page", "paid", "pail", "pain", "paine", "paint", "pair", "pal", "pale", "pall", "palm", "palo", "palsy", "pam", "pampa", "pan", "panama", "panda", "pane", "panel", "pang", "panic", "pansy", "pant", "panty", "paoli", "pap", "papa", "papal", "papaw", "paper", "pappy", "papua", "par", "parch", "pardon", "pare", "pareto", "paris", "park", "parke", "parks", "parr", "parry", "parse", "part", "party", "pascal", "pasha", "paso", "pass", "passe", "past", "paste", "pasty", "pat", "patch", "pate", "pater", "path", "patio", "patsy", "patti", "patton", "patty", "paul", "paula", "pauli", "paulo", "pause", "pave", "paw", "pawn", "pax", "pay", "payday", "payne", "paz", "pbs", "pea", "peace", "peach", "peak", "peaky", "peal", "peale", "pear", "pearl", "pease", "peat", "pebble", "pecan", "peck", "pecos", "pedal", "pedro", "pee", "peed", "peek", "peel", "peep", "peepy", "peer", "peg", "peggy", "pelt", "pen", "penal", "pence", "pencil", "pend", "penh", "penn", "penna", "penny", "pent", "peony", "pep", "peppy", "pepsi", "per", "perch", "percy", "perez", "peril", "perk", "perky", "perle", "perry", "persia", "pert", "perth", "peru", "peruse", "pest", "peste", "pet", "petal", "pete", "peter", "petit", "petri", "petty", "pew", "pewee", "phage", "phase", "phd", "phenol", "phi", "phil", "phlox", "phon", "phone", "phony", "photo", "phyla", "physic", "piano", "pica", "pick", "pickup", "picky", "pie", "piece", "pier", "pierce", "piety", "pig", "piggy", "pike", "pile", "pill", "pilot", "pimp", "pin", "pinch", "pine", "ping", "pinion", "pink", "pint", "pinto", "pion", "piotr", "pious", "pip", "pipe", "piper", "pique", "pit", "pitch", "pith", "pithy", "pitney", "pitt", "pity", "pius", "pivot", "pixel", "pixy", "pizza", "place", "plague", "plaid", "plain", "plan", "plane", "plank", "plant", "plasm", "plat", "plate", "plato", "play", "playa", "plaza", "plea", "plead", "pleat", "pledge", "pliny", "plod", "plop", "plot", "plow", "pluck", "plug", "plum", "plumb", "plume", "plump", "plunk", "plus", "plush", "plushy", "pluto", "ply", "poach", "pobox", "pod", "podge", "podia", "poe", "poem", "poesy", "poet", "poetry", "pogo", "poi", "point", "poise", "poke", "pol", "polar", "pole", "police", "polio", "polis", "polk", "polka", "poll", "polo", "pomona", "pomp", "ponce", "pond", "pong", "pont", "pony", "pooch", "pooh", "pool", "poole", "poop", "poor", "pop", "pope", "poppy", "porch", "pore", "pork", "porous", "port", "porte", "portia", "porto", "pose", "posey", "posh", "posit", "posse", "post", "posy", "pot", "potts", "pouch", "pound", "pour", "pout", "pow", "powder", "power", "ppm", "ppp", "pppp", "pqr", "prado", "pram", "prank", "pratt", "pray", "preen", "prefix", "prep", "press", "prexy", "prey", "priam", "price", "prick", "pride", "prig", "prim", "prima", "prime", "primp", "prince", "print", "prior", "prism", "prissy", "privy", "prize", "pro", "probe", "prod", "prof", "prom", "prone", "prong", "proof", "prop", "propyl", "prose", "proud", "prove", "prow", "prowl", "proxy", "prune", "pry", "psalm", "psi", "psych", "pta", "pub", "puck", "puddly", "puerto", "puff", "puffy", "pug", "pugh", "puke", "pull", "pulp", "pulse", "puma", "pump", "pun", "punch", "punic", "punish", "punk", "punky", "punt", "puny", "pup", "pupal", "pupil", "puppy", "pure", "purge", "purl", "purr", "purse", "pus", "pusan", "pusey", "push", "pussy", "put", "putt", "putty", "pvc", "pygmy", "pyle", "pyre", "pyrex", "pyrite", "qatar", "qed", "qqq", "qqqq", "qrs", "qua", "quack", "quad", "quaff", "quail", "quake", "qualm", "quark", "quarry", "quart", "quash", "quasi", "quay", "queasy", "queen", "queer", "quell", "query", "quest", "queue", "quick", "quid", "quiet", "quill", "quilt", "quinn", "quint", "quip", "quirk", "quirt", "quit", "quite", "quito", "quiz", "quo", "quod", "quota", "quote", "rabat", "rabbi", "rabbit", "rabid", "rabin", "race", "rack", "racy", "radar", "radii", "radio", "radium", "radix", "radon", "rae", "rafael", "raft", "rag", "rage", "raid", "rail", "rain", "rainy", "raise", "raj", "rajah", "rake", "rally", "ralph", "ram", "raman", "ramo", "ramp", "ramsey", "ran", "ranch", "rand", "randy", "rang", "range", "rangy", "rank", "rant", "raoul", "rap", "rape", "rapid", "rapt", "rare", "rasa", "rascal", "rash", "rasp", "rat", "rata", "rate", "rater", "ratio", "rattle", "raul", "rave", "ravel", "raven", "raw", "ray", "raze", "razor", "rca", "reach", "read", "ready", "reagan", "real", "realm", "ream", "reap", "rear", "reave", "reb", "rebel", "rebut", "recipe", "reck", "recur", "red", "redeem", "reduce", "reed", "reedy", "reef", "reek", "reel", "reese", "reeve", "refer", "regal", "regina", "regis", "reich", "reid", "reign", "rein", "relax", "relay", "relic", "reman", "remedy", "remit", "remus", "rena", "renal", "rend", "rene", "renown", "rent", "rep", "repel", "repent", "resin", "resort", "rest", "ret", "retch", "return", "reub", "rev", "reveal", "revel", "rever", "revet", "revved", "rex", "rhea", "rheum", "rhine", "rhino", "rho", "rhoda", "rhode", "rhyme", "rib", "rica", "rice", "rich", "rick", "rico", "rid", "ride", "ridge", "rifle", "rift", "rig", "riga", "rigel", "riggs", "right", "rigid", "riley", "rill", "rilly", "rim", "rime", "rimy", "ring", "rink", "rinse", "rio", "riot", "rip", "ripe", "ripen", "ripley", "rise", "risen", "risk", "risky", "rite", "ritz", "rival", "riven", "river", "rivet", "riyadh", "roach", "road", "roam", "roar", "roast", "rob", "robe", "robin", "robot", "rock", "rocket", "rocky", "rod", "rode", "rodeo", "roe", "roger", "rogue", "roil", "role", "roll", "roman", "rome", "romeo", "romp", "ron", "rondo", "rood", "roof", "rook", "rookie", "rooky", "room", "roomy", "roost", "root", "rope", "rosa", "rose", "rosen", "ross", "rosy", "rot", "rotc", "roth", "rotor", "rouge", "rough", "round", "rouse", "rout", "route", "rove", "row", "rowdy", "rowe", "roy", "royal", "royce", "rpm", "rrr", "rrrr", "rst", "rsvp", "ruanda", "rub", "rube", "ruben", "rubin", "rubric", "ruby", "ruddy", "rude", "rudy", "rue", "rufus", "rug", "ruin", "rule", "rum", "rumen", "rummy", "rump", "rumpus", "run", "rune", "rung", "runge", "runic", "runt", "runty", "rupee", "rural", "ruse", "rush", "rusk", "russ", "russo", "rust", "rusty", "rut", "ruth", "rutty", "ryan", "ryder", "rye", "sabine", "sable", "sabra", "sac", "sachs", "sack", "sad", "saddle", "sadie", "safari", "safe", "sag", "saga", "sage", "sago", "said", "sail", "saint", "sake", "sal", "salad", "sale", "salem", "saline", "salk", "salle", "sally", "salon", "salt", "salty", "salve", "salvo", "sam", "samba", "same", "sammy", "samoa", "samuel", "san", "sana", "sand", "sandal", "sandy", "sane", "sang", "sank", "sans", "santa", "santo", "sao", "sap", "sappy", "sara", "sarah", "saran", "sari", "sash", "sat", "satan", "satin", "satyr", "sauce", "saucy", "saud", "saudi", "saul", "sault", "saute", "save", "savoy", "savvy", "saw", "sawyer", "sax", "saxon", "say", "scab", "scala", "scald", "scale", "scalp", "scam", "scamp", "scan", "scant", "scar", "scare", "scarf", "scary", "scat", "scaup", "scene", "scent", "school", "scion", "scm", "scoff", "scold", "scoop", "scoot", "scope", "scops", "score", "scoria", "scorn", "scot", "scott", "scour", "scout", "scowl", "scram", "scrap", "scrape", "screw", "scrim", "scrub", "scuba", "scud", "scuff", "scull", "scum", "scurry", "sea", "seal", "seam", "seamy", "sean", "sear", "sears", "season", "seat", "sec", "secant", "sect", "sedan", "seder", "sedge", "see", "seed", "seedy", "seek", "seem", "seen", "seep", "seethe", "seize", "self", "sell", "selma", "semi", "sen", "send", "seneca", "senor", "sense", "sent", "sentry", "seoul", "sepal", "sepia", "sepoy", "sept", "septa", "sequin", "sera", "serf", "serge", "serif", "serum", "serve", "servo", "set", "seth", "seton", "setup", "seven", "sever", "severe", "sew", "sewn", "sex", "sexy", "shack", "shad", "shade", "shady", "shafer", "shaft", "shag", "shah", "shake", "shaken", "shako", "shaky", "shale", "shall", "sham", "shame", "shank", "shape", "shard", "share", "shari", "shark", "sharp", "shave", "shaw", "shawl", "shay", "she", "shea", "sheaf", "shear", "sheath", "shed", "sheen", "sheep", "sheer", "sheet", "sheik", "shelf", "shell", "shied", "shift", "shill", "shim", "shin", "shine", "shinto", "shiny", "ship", "shire", "shirk", "shirt", "shish", "shiv", "shoal", "shock", "shod", "shoe", "shoji", "shone", "shoo", "shook", "shoot", "shop", "shore", "short", "shot", "shout", "shove", "show", "shown", "showy", "shrank", "shred", "shrew", "shrike", "shrub", "shrug", "shu", "shuck", "shun", "shunt", "shut", "shy", "sial", "siam", "sian", "sib", "sibley", "sibyl", "sic", "sick", "side", "sidle", "siege", "siena", "sieve", "sift", "sigh", "sight", "sigma", "sign", "signal", "signor", "silas", "silk", "silky", "sill", "silly", "silo", "silt", "silty", "sima", "simon", "simons", "sims", "sin", "sinai", "since", "sine", "sinew", "sing", "singe", "sinh", "sink", "sinus", "sioux", "sip", "sir", "sire", "siren", "sis", "sisal", "sit", "site", "situ", "situs", "siva", "six", "sixgun", "sixth", "sixty", "size", "skat", "skate", "skeet", "skew", "ski", "skid", "skied", "skiff", "skill", "skim", "skimp", "skimpy", "skin", "skip", "skirt", "skit", "skulk", "skull", "skunk", "sky", "skye", "slab", "slack", "slag", "slain", "slake", "slam", "slang", "slant", "slap", "slash", "slat", "slate", "slater", "slav", "slave", "slay", "sled", "sleek", "sleep", "sleet", "slept", "slew", "slice", "slick", "slid", "slide", "slim", "slime", "slimy", "sling", "slip", "slit", "sliver", "sloan", "slob", "sloe", "slog", "sloop", "slop", "slope", "slosh", "slot", "sloth", "slow", "slug", "sluice", "slum", "slump", "slung", "slur", "slurp", "sly", "smack", "small", "smart", "smash", "smear", "smell", "smelt", "smile", "smirk", "smith", "smithy", "smog", "smoke", "smoky", "smug", "smut", "snack", "snafu", "snag", "snail", "snake", "snap", "snare", "snark", "snarl", "snatch", "sneak", "sneer", "snell", "snick", "sniff", "snip", "snipe", "snob", "snook", "snoop", "snore", "snort", "snout", "snow", "snowy", "snub", "snuff", "snug", "soak", "soap", "soapy", "soar", "sob", "sober", "social", "sock", "sod", "soda", "sofa", "sofia", "soft", "soften", "soggy", "soil", "sol", "solar", "sold", "sole", "solemn", "solid", "solo", "solon", "solve", "soma", "somal", "some", "son", "sonar", "song", "sonic", "sonny", "sonora", "sony", "soon", "soot", "sooth", "sop", "sora", "sorb", "sore", "sorry", "sort", "sos", "sou", "sough", "soul", "sound", "soup", "sour", "source", "sousa", "south", "sow", "sown", "soy", "soya", "spa", "space", "spade", "spain", "span", "spar", "spare", "sparge", "spark", "spasm", "spat", "spate", "spawn", "spay", "speak", "spear", "spec", "speck", "sped", "speed", "spell", "spend", "spent", "sperm", "sperry", "spew", "spica", "spice", "spicy", "spike", "spiky", "spill", "spilt", "spin", "spine", "spiny", "spire", "spiro", "spit", "spite", "spitz", "splat", "splay", "spline", "split", "spoil", "spoke", "spoof", "spook", "spooky", "spool", "spoon", "spore", "sport", "spot", "spout", "sprain", "spray", "spree", "sprig", "spruce", "sprue", "spud", "spume", "spun", "spunk", "spur", "spurn", "spurt", "spy", "squad", "squat", "squaw", "squibb", "squid", "squint", "sri", "sss", "ssss", "sst", "st.", "stab", "stack", "stacy", "staff", "stag", "stage", "stagy", "stahl", "staid", "stain", "stair", "stake", "stale", "stalk", "stall", "stamp", "stan", "stance", "stand", "stank", "staph", "star", "stare", "stark", "starr", "start", "stash", "state", "statue", "stave", "stay", "stead", "steak", "steal", "steam", "steed", "steel", "steele", "steen", "steep", "steer", "stein", "stella", "stem", "step", "stern", "steve", "stew", "stick", "stiff", "stile", "still", "stilt", "sting", "stingy", "stink", "stint", "stir", "stock", "stoic", "stoke", "stole", "stomp", "stone", "stony", "stood", "stool", "stoop", "stop", "store", "storey", "stork", "storm", "story", "stout", "stove", "stow", "strafe", "strap", "straw", "stray", "strewn", "strip", "stroll", "strom", "strop", "strum", "strut", "stu", "stuart", "stub", "stuck", "stud", "study", "stuff", "stuffy", "stump", "stun", "stung", "stunk", "stunt", "sturm", "style", "styli", "styx", "suave", "sub", "subtly", "such", "suck", "sud", "sudan", "suds", "sue", "suey", "suez", "sugar", "suit", "suite", "sulfa", "sulk", "sulky", "sully", "sultry", "sum", "sumac", "summon", "sun", "sung", "sunk", "sunny", "sunset", "suny", "sup", "super", "supra", "sure", "surf", "surge", "sus", "susan", "sushi", "susie", "sutton", "swab", "swag", "swain", "swam", "swami", "swamp", "swampy", "swan", "swank", "swap", "swarm", "swart", "swat", "swath", "sway", "swear", "sweat", "sweaty", "swede", "sweep", "sweet", "swell", "swelt", "swept", "swift", "swig", "swim", "swine", "swing", "swipe", "swirl", "swish", "swiss", "swoop", "sword", "swore", "sworn", "swum", "swung", "sybil", "sykes", "sylow", "sylvan", "synge", "synod", "syria", "syrup", "tab", "table", "taboo", "tabu", "tabula", "tacit", "tack", "tacky", "tacoma", "tact", "tad", "taffy", "taft", "tag", "tahoe", "tail", "taint", "take", "taken", "talc", "tale", "talk", "talky", "tall", "tallow", "tally", "talon", "talus", "tam", "tame", "tamp", "tampa", "tan", "tang", "tango", "tangy", "tanh", "tank", "tansy", "tanya", "tao", "taos", "tap", "tapa", "tape", "taper", "tapir", "tapis", "tappa", "tar", "tara", "tardy", "tariff", "tarry", "tart", "task", "tass", "taste", "tasty", "tat", "tate", "tater", "tattle", "tatty", "tau", "taunt", "taut", "tavern", "tawny", "tax", "taxi", "tea", "teach", "teal", "team", "tear", "tease", "teat", "tech", "tecum", "ted", "teddy", "tee", "teem", "teen", "teensy", "teet", "teeth", "telex", "tell", "tempo", "tempt", "ten", "tend", "tenet", "tenney", "tenon", "tenor", "tense", "tensor", "tent", "tenth", "tepee", "tepid", "term", "tern", "terra", "terre", "terry", "terse", "tess", "test", "testy", "tete", "texan", "texas", "text", "thai", "than", "thank", "that", "thaw", "the", "thea", "thee", "theft", "their", "them", "theme", "then", "there", "these", "theta", "they", "thick", "thief", "thigh", "thin", "thine", "thing", "think", "third", "this", "thong", "thor", "thorn", "thorny", "those", "thou", "thread", "three", "threw", "throb", "throes", "throw", "thrum", "thud", "thug", "thule", "thumb", "thump", "thus", "thy", "thyme", "tiber", "tibet", "tibia", "tic", "tick", "ticket", "tid", "tidal", "tidbit", "tide", "tidy", "tie", "tied", "tier", "tift", "tiger", "tight", "til", "tilde", "tile", "till", "tilt", "tilth", "tim", "time", "timex", "timid", "timon", "tin", "tina", "tine", "tinge", "tint", "tiny", "tioga", "tip", "tipoff", "tippy", "tipsy", "tire", "tit", "titan", "tithe", "title", "titus", "tnt", "toad", "toady", "toast", "toby", "today", "todd", "toe", "tofu", "tog", "togo", "togs", "toil", "toilet", "token", "tokyo", "told", "toll", "tom", "tomb", "tome", "tommy", "ton", "tonal", "tone", "tong", "toni", "tonic", "tonk", "tonsil", "tony", "too", "took", "tool", "toot", "tooth", "top", "topaz", "topic", "topple", "topsy", "tor", "torah", "torch", "tore", "tori", "torn", "torr", "torso", "tort", "torus", "tory", "toss", "tot", "total", "tote", "totem", "touch", "tough", "tour", "tout", "tow", "towel", "tower", "town", "toxic", "toxin", "toy", "trace", "track", "tract", "tracy", "trade", "trag", "trail", "train", "trait", "tram", "tramp", "trap", "trash", "trawl", "tread", "treat", "treble", "tree", "trek", "trench", "trend", "tress", "triad", "trial", "tribe", "trick", "tried", "trig", "trill", "trim", "trio", "trip", "tripe", "trite", "triton", "trod", "troll", "troop", "trot", "trout", "troy", "truce", "truck", "trudge", "trudy", "true", "truly", "trump", "trunk", "truss", "trust", "truth", "trw", "try", "tsar", "ttl", "ttt", "tttt", "tty", "tub", "tuba", "tube", "tuck", "tudor", "tuff", "tuft", "tug", "tulane", "tulip", "tulle", "tulsa", "tum", "tun", "tuna", "tune", "tung", "tunic", "tunis", "tunnel", "tuple", "turf", "turin", "turk", "turn", "turvy", "tusk", "tussle", "tutor", "tutu", "tuv", "tva", "twa", "twain", "tweak", "tweed", "twice", "twig", "twill", "twin", "twine", "twirl", "twist", "twisty", "twit", "two", "twx", "tyburn", "tying", "tyler", "type", "typic", "typo", "tyson", "ucla", "ugh", "ugly", "ulan", "ulcer", "ultra", "umber", "umbra", "umpire", "unary", "uncle", "under", "unify", "union", "unit", "unite", "unity", "unix", "until", "upend", "uphold", "upon", "upper", "uproar", "upset", "uptake", "upton", "urban", "urbane", "urea", "urge", "uri", "urine", "uris", "urn", "ursa", "usa", "usaf", "usage", "usc", "usda", "use", "useful", "usgs", "usher", "usia", "usn", "usps", "ussr", "usual", "usurp", "usury", "utah", "utica", "utile", "utmost", "utter", "uuu", "uuuu", "uvw", "vacua", "vacuo", "vade", "vaduz", "vague", "vail", "vain", "vale", "valet", "valeur", "valid", "value", "valve", "vamp", "van", "vance", "vane", "vary", "vase", "vast", "vat", "vault", "veal", "veda", "vee", "veer", "veery", "vega", "veil", "vein", "velar", "veldt", "vella", "vellum", "venal", "vend", "venial", "venom", "vent", "venus", "vera", "verb", "verde", "verdi", "verge", "verity", "verna", "verne", "versa", "verse", "verve", "very", "vessel", "vest", "vet", "vetch", "veto", "vex", "via", "vial", "vicar", "vice", "vichy", "vicky", "vida", "video", "vie", "viet", "view", "vigil", "vii", "viii", "vile", "villa", "vine", "vinyl", "viola", "violet", "virgil", "virgo", "virus", "vis", "visa", "vise", "visit", "visor", "vista", "vita", "vitae", "vital", "vito", "vitro", "viva", "vivian", "vivid", "vivo", "vixen", "viz", "vocal", "vogel", "vogue", "voice", "void", "volt", "volta", "volvo", "vomit", "von", "voss", "vote", "vouch", "vow", "vowel", "vulcan", "vvv", "vvvv", "vying", "waals", "wac", "wack", "wacke", "wacky", "waco", "wad", "wade", "wadi", "wafer", "wag", "wage", "waggle", "wah", "wahl", "wail", "waist", "wait", "waite", "waive", "wake", "waken", "waldo", "wale", "walk", "walkie", "wall", "walls", "wally", "walsh", "walt", "walton", "waltz", "wan", "wand", "wane", "wang", "want", "war", "ward", "ware", "warm", "warmth", "warn", "warp", "warren", "wart", "warty", "wary", "was", "wash", "washy", "wasp", "wast", "waste", "watch", "water", "watt", "watts", "wave", "wavy", "wax", "waxen", "waxy", "way", "wayne", "weak", "weal", "wealth", "wean", "wear", "weary", "weave", "web", "webb", "weber", "weco", "wed", "wedge", "wee", "weed", "weedy", "week", "weeks", "weep", "wehr", "wei", "weigh", "weir", "weird", "weiss", "welch", "weld", "well", "wells", "welsh", "welt", "wendy", "went", "wept", "were", "wert", "west", "wet", "whack", "whale", "wham", "wharf", "what", "wheat", "whee", "wheel", "whelk", "whelm", "whelp", "when", "where", "whet", "which", "whiff", "whig", "while", "whim", "whine", "whinny", "whip", "whir", "whirl", "whisk", "whit", "white", "whiz", "who", "whoa", "whole", "whom", "whoop", "whoosh", "whop", "whose", "whup", "why", "wick", "wide", "widen", "widow", "width", "wield", "wier", "wife", "wig", "wild", "wile", "wiley", "wilkes", "will", "willa", "wills", "wilma", "wilt", "wily", "win", "wince", "winch", "wind", "windy", "wine", "wing", "wink", "winnie", "wino", "winter", "winy", "wipe", "wire", "wiry", "wise", "wish", "wishy", "wisp", "wispy", "wit", "witch", "with", "withe", "withy", "witt", "witty", "wive", "woe", "wok", "woke", "wold", "wolf", "wolfe", "wolff", "wolve", "woman", "womb", "women", "won", "wonder", "wong", "wont", "woo", "wood", "woods", "woody", "wool", "woozy", "word", "wordy", "wore", "work", "world", "worm", "wormy", "worn", "worry", "worse", "worst", "worth", "wotan", "would", "wound", "wove", "woven", "wow", "wrack", "wrap", "wrath", "wreak", "wreck", "wrest", "wring", "wrist", "writ", "write", "writhe", "wrong", "wrote", "wry", "wuhan", "www", "wwww", "wxy", "wyatt", "wyeth", "wylie", "wyman", "wyner", "wynn", "xenon", "xerox", "xxx", "xxxx", "xylem", "xyz", "yacht", "yah", "yak", "yale", "yalta", "yam", "yamaha", "yang", "yank", "yap", "yaqui", "yard", "yarn", "yates", "yaw", "yawl", "yawn", "yea", "yeah", "year", "yearn", "yeast", "yeasty", "yeats", "yell", "yelp", "yemen", "yen", "yet", "yield", "yin", "yip", "ymca", "yodel", "yoder", "yoga", "yogi", "yoke", "yokel", "yolk", "yon", "yond", "yore", "york", "yost", "you", "young", "your", "youth", "yow", "yucca", "yuck", "yuh", "yuki", "yukon", "yule", "yves", "ywca", "yyy", "yyyy", "zag", "zaire", "zan", "zap", "zazen", "zeal", "zealot", "zebra", "zeiss", "zen", "zero", "zest", "zesty", "zeta", "zeus", "zig", "zilch", "zinc", "zing", "zion", "zip", "zloty", "zoe", "zomba", "zone", "zoo", "zoom", "zorn", "zurich", "zzz", "zzzz"]
14.535698
15
0.312151
wl = ["aah", "aaron", "aba", "ababa", "aback", "abase", "abash", "abate", "abbas", "abbe", "abbey", "abbot", "abbott", "abc", "abe", "abed", "abel", "abet", "abide", "abject", "ablaze", "able", "abner", "abo", "abode", "abort", "about", "above", "abrade", "abram", "absorb", "abuse", "abut", "abyss", "acadia", "accra", "accrue", "ace", "acetic", "ache", "acid", "acidic", "acm", "acme", "acorn", "acre", "acrid", "act", "acton", "actor", "acts", "acuity", "acute", "ada", "adage", "adagio", "adair", "adam", "adams", "adapt", "add", "added", "addict", "addis", "addle", "adele", "aden", "adept", "adieu", "adjust", "adler", "admit", "admix", "ado", "adobe", "adonis", "adopt", "adore", "adorn", "adult", "advent", "advert", "advise", "aegis", "aeneid", "afar", "affair", "affine", "affix", "afire", "afoot", "afraid", "africa", "afro", "aft", "again", "agate", "agave", "age", "age", "agenda", "agent", "agile", "aging", "agnes", "agnew", "ago", "agone", "agony", "agree", "ague", "agway", "ahead", "ahem", "ahoy", "aid", "aida", "aide", "aides", "aiken", "ail", "aile", "aim", "ainu", "air", "aires", "airman", "airway", "airy", "aisle", "ajar", "ajax", "akers", "akin", "akron", "ala", "alai", "alamo", "alan", "alarm", "alaska", "alb", "alba", "album", "alcoa", "alden", "alder", "ale", "alec", "aleck", "aleph", "alert", "alex", "alexei", "alga", "algae", "algal", "alger", "algol", "ali", "alia", "alias", "alibi", "alice", "alien", "alight", "align", "alike", "alive", "all", "allah", "allan", "allay", "allen", "alley", "allied", "allis", "allot", "allow", "alloy", "allure", "ally", "allyl", "allyn", "alma", "almost", "aloe", "aloft", "aloha", "alone", "along", "aloof", "aloud", "alp", "alpha", "alps", "also", "alsop", "altair", "altar", "alter", "alto", "alton", "alum", "alumni", "alva", "alvin", "alway", "ama", "amass", "amaze", "amber", "amble", "ambush", "amen", "amend", "ames", "ami", "amid", "amide", "amigo", "amino", "amiss", "amity", "amman", "ammo", "amoco", "amok", "among", "amort", "amos", "amp", "ampere", "ampex", "ample", "amply", "amra", "amulet", "amuse", "amy", "ana", "and", "andes", "andre", "andrew", "andy", "anent", "anew", "angel", "angelo", "anger", "angie", "angle", "anglo", "angola", "angry", "angst", "angus", "ani", "anion", "anise", "anita", "ankle", "ann", "anna", "annal", "anne", "annex", "annie", "annoy", "annul", "annuli", "annum", "anode", "ansi", "answer", "ant", "ante", "anti", "antic", "anton", "anus", "anvil", "any", "anyhow", "anyway", "aok", "aorta", "apart", "apathy", "ape", "apex", "aphid", "aplomb", "appeal", "append", "apple", "apply", "april", "apron", "apse", "apt", "aqua", "arab", "araby", "arc", "arcana", "arch", "archer", "arden", "ardent", "are", "area", "arena", "ares", "argive", "argo", "argon", "argot", "argue", "argus", "arhat", "arid", "aries", "arise", "ark", "arlen", "arlene", "arm", "armco", "army", "arnold", "aroma", "arose", "arpa", "array", "arrear", "arrow", "arson", "art", "artery", "arthur", "artie", "arty", "aruba", "arum", "aryl", "ascend", "ash", "ashen", "asher", "ashley", "ashy", "asia", "aside", "ask", "askew", "asleep", "aspen", "aspire", "ass", "assai", "assam", "assay", "asset", "assort", "assure", "aster", "astm", "astor", "astral", "ate", "athens", "atlas", "atom", "atomic", "atone", "atop", "attic", "attire", "aubrey", "audio", "audit", "aug", "auger", "augur", "august", "auk", "aunt", "aura", "aural", "auric", "austin", "auto", "autumn", "avail", "ave", "aver", "avert", "avery", "aviate", "avid", "avis", "aviv", "avoid", "avon", "avow", "await", "awake", "award", "aware", "awash", "away", "awe", "awful", "awl", "awn", "awoke", "awry", "axe", "axes", "axial", "axiom", "axis", "axle", "axon", "aye", "ayers", "aztec", "azure", "babe", "babel", "baby", "bach", "back", "backup", "bacon", "bad", "bade", "baden", "badge", "baffle", "bag", "baggy", "bah", "bahama", "bail", "baird", "bait", "bake", "baku", "bald", "baldy", "bale", "bali", "balk", "balkan", "balky", "ball", "balled", "ballot", "balm", "balmy", "balsa", "bam", "bambi", "ban", "banal", "band", "bandit", "bandy", "bane", "bang", "banish", "banjo", "bank", "banks", "bantu", "bar", "barb", "bard", "bare", "barfly", "barge", "bark", "barley", "barn", "barnes", "baron", "barony", "barr", "barre", "barry", "barter", "barth", "barton", "basal", "base", "basel", "bash", "basic", "basil", "basin", "basis", "bask", "bass", "bassi", "basso", "baste", "bat", "batch", "bate", "bater", "bates", "bath", "bathe", "batik", "baton", "bator", "batt", "bauble", "baud", "bauer", "bawd", "bawdy", "bawl", "baxter", "bay", "bayda", "bayed", "bayou", "bazaar", "bbb", "bbbb", "bcd", "beach", "bead", "beady", "beak", "beam", "bean", "bear", "beard", "beast", "beat", "beau", "beauty", "beaux", "bebop", "becalm", "beck", "becker", "becky", "bed", "bedim", "bee", "beebe", "beech", "beef", "beefy", "been", "beep", "beer", "beet", "befall", "befit", "befog", "beg", "began", "beget", "beggar", "begin", "begun", "behind", "beige", "being", "beirut", "bel", "bela", "belch", "belfry", "belie", "bell", "bella", "belle", "belly", "below", "belt", "bema", "beman", "bemoan", "ben", "bench", "bend", "bender", "benny", "bent", "benz", "berea", "bereft", "beret", "berg", "berlin", "bern", "berne", "bernet", "berra", "berry", "bert", "berth", "beryl", "beset", "bess", "bessel", "best", "bestir", "bet", "beta", "betel", "beth", "bethel", "betsy", "bette", "betty", "bevel", "bevy", "beware", "bey", "bezel", "bhoy", "bias", "bib", "bibb", "bible", "bicep", "biceps", "bid", "biddy", "bide", "bien", "big", "biggs", "bigot", "bile", "bilge", "bilk", "bill", "billow", "billy", "bin", "binary", "bind", "bing", "binge", "bingle", "bini", "biota", "birch", "bird", "birdie", "birth", "bison", "bisque", "bit", "bitch", "bite", "bitt", "bitten", "biz", "bizet", "blab", "black", "blade", "blair", "blake", "blame", "blanc", "bland", "blank", "blare", "blast", "blat", "blatz", "blaze", "bleak", "bleat", "bled", "bleed", "blend", "bless", "blest", "blew", "blimp", "blind", "blink", "blinn", "blip", "bliss", "blithe", "blitz", "bloat", "blob", "bloc", "bloch", "block", "bloke", "blond", "blonde", "blood", "bloom", "bloop", "blot", "blotch", "blow", "blown", "blue", "bluet", "bluff", "blum", "blunt", "blur", "blurt", "blush", "blvd", "blythe", "bmw", "boa", "boar", "board", "boast", "boat", "bob", "bobbin", "bobby", "bobcat", "boca", "bock", "bode", "body", "bog", "bogey", "boggy", "bogus", "bogy", "bohr", "boil", "bois", "boise", "bold", "bole", "bolo", "bolt", "bomb", "bombay", "bon", "bona", "bond", "bone", "bong", "bongo", "bonn", "bonus", "bony", "bonze", "boo", "booby", "boogie", "book", "booky", "boom", "boon", "boone", "boor", "boost", "boot", "booth", "booty", "booze", "bop", "borax", "border", "bore", "borg", "boric", "boris", "born", "borne", "borneo", "boron", "bosch", "bose", "bosom", "boson", "boss", "boston", "botch", "both", "bottle", "bough", "bouncy", "bound", "bourn", "bout", "bovine", "bow", "bowel", "bowen", "bowie", "bowl", "box", "boxy", "boy", "boyar", "boyce", "boyd", "boyle", "brace", "bract", "brad", "brady", "brae", "brag", "bragg", "braid", "brain", "brainy", "brake", "bran", "brand", "brandt", "brant", "brash", "brass", "brassy", "braun", "brave", "bravo", "brawl", "bray", "bread", "break", "bream", "breath", "bred", "breed", "breeze", "bremen", "brent", "brest", "brett", "breve", "brew", "brian", "briar", "bribe", "brice", "brick", "bride", "brief", "brig", "briggs", "brim", "brine", "bring", "brink", "briny", "brisk", "broad", "brock", "broil", "broke", "broken", "bronx", "brood", "brook", "brooke", "broom", "broth", "brow", "brown", "browse", "bruce", "bruit", "brunch", "bruno", "brunt", "brush", "brute", "bryan", "bryant", "bryce", "bryn", "bstj", "btl", "bub", "buck", "bud", "budd", "buddy", "budge", "buena", "buenos", "buff", "bug", "buggy", "bugle", "buick", "build", "built", "bulb", "bulge", "bulk", "bulky", "bull", "bully", "bum", "bump", "bun", "bunch", "bundy", "bunk", "bunny", "bunt", "bunyan", "buoy", "burch", "bureau", "buret", "burg", "buried", "burke", "burl", "burly", "burma", "burn", "burnt", "burp", "burr", "burro", "burst", "burt", "burton", "burtt", "bury", "bus", "busch", "bush", "bushel", "bushy", "buss", "bust", "busy", "but", "butane", "butch", "buteo", "butt", "butte", "butyl", "buxom", "buy", "buyer", "buzz", "buzzy", "bye", "byers", "bylaw", "byline", "byrd", "byrne", "byron", "byte", "byway", "byword", "cab", "cabal", "cabin", "cable", "cabot", "cacao", "cache", "cacm", "cacti", "caddy", "cadent", "cadet", "cadre", "cady", "cafe", "cage", "cagey", "cahill", "caiman", "cain", "caine", "cairn", "cairo", "cake", "cal", "calder", "caleb", "calf", "call", "calla", "callus", "calm", "calve", "cam", "camber", "came", "camel", "cameo", "camp", "can", "canal", "canary", "cancer", "candle", "candy", "cane", "canis", "canna", "cannot", "canny", "canoe", "canon", "canopy", "cant", "canto", "canton", "cap", "cape", "caper", "capo", "car", "carbon", "card", "care", "caress", "caret", "carey", "cargo", "carib", "carl", "carla", "carlo", "carne", "carob", "carol", "carp", "carpet", "carr", "carrie", "carry", "carson", "cart", "carte", "caruso", "carve", "case", "casey", "cash", "cashew", "cask", "casket", "cast", "caste", "cat", "catch", "cater", "cathy", "catkin", "catsup", "cauchy", "caulk", "cause", "cave", "cavern", "cavil", "cavort", "caw", "cayuga", "cbs", "ccc", "cccc", "cdc", "cease", "cecil", "cedar", "cede", "ceil", "celia", "cell", "census", "cent", "ceres", "cern", "cetera", "cetus", "chad", "chafe", "chaff", "chai", "chain", "chair", "chalk", "champ", "chance", "chang", "chant", "chao", "chaos", "chap", "chapel", "char", "chard", "charm", "chart", "chase", "chasm", "chaste", "chat", "chaw", "cheap", "cheat", "check", "cheek", "cheeky", "cheer", "chef", "chen", "chert", "cherub", "chess", "chest", "chevy", "chew", "chi", "chic", "chick", "chide", "chief", "child", "chile", "chili", "chill", "chilly", "chime", "chin", "china", "chine", "chink", "chip", "chirp", "chisel", "chit", "chive", "chock", "choir", "choke", "chomp", "chop", "chopin", "choral", "chord", "chore", "chose", "chosen", "chou", "chow", "chris", "chub", "chuck", "chuff", "chug", "chum", "chump", "chunk", "churn", "chute", "cia", "cicada", "cider", "cigar", "cilia", "cinch", "cindy", "cipher", "circa", "circe", "cite", "citrus", "city", "civet", "civic", "civil", "clad", "claim", "clam", "clammy", "clamp", "clan", "clang", "clank", "clap", "clara", "clare", "clark", "clarke", "clash", "clasp", "class", "claus", "clause", "claw", "clay", "clean", "clear", "cleat", "cleft", "clerk", "cliche", "click", "cliff", "climb", "clime", "cling", "clink", "clint", "clio", "clip", "clive", "cloak", "clock", "clod", "clog", "clomp", "clone", "close", "closet", "clot", "cloth", "cloud", "clout", "clove", "clown", "cloy", "club", "cluck", "clue", "cluj", "clump", "clumsy", "clung", "clyde", "coach", "coal", "coast", "coat", "coax", "cobb", "cobble", "cobol", "cobra", "coca", "cock", "cockle", "cocky", "coco", "cocoa", "cod", "coda", "coddle", "code", "codon", "cody", "coed", "cog", "cogent", "cohen", "cohn", "coil", "coin", "coke", "col", "cola", "colby", "cold", "cole", "colon", "colony", "colt", "colza", "coma", "comb", "combat", "come", "comet", "cometh", "comic", "comma", "con", "conch", "cone", "coney", "congo", "conic", "conn", "conner", "conway", "cony", "coo", "cook", "cooke", "cooky", "cool", "cooley", "coon", "coop", "coors", "coot", "cop", "cope", "copra", "copy", "coral", "corbel", "cord", "core", "corey", "cork", "corn", "corny", "corp", "corps", "corvus", "cos", "cosec", "coset", "cosh", "cost", "costa", "cosy", "cot", "cotta", "cotty", "couch", "cough", "could", "count", "coup", "coupe", "court", "cousin", "cove", "coven", "cover", "covet", "cow", "cowan", "cowl", "cowman", "cowry", "cox", "coy", "coyote", "coypu", "cozen", "cozy", "cpa", "crab", "crack", "craft", "crag", "craig", "cram", "cramp", "crane", "crank", "crap", "crash", "crass", "crate", "crater", "crave", "craw", "crawl", "craze", "crazy", "creak", "cream", "credit", "credo", "creed", "creek", "creep", "creole", "creon", "crepe", "crept", "cress", "crest", "crete", "crew", "crib", "cried", "crime", "crimp", "crisp", "criss", "croak", "crock", "crocus", "croft", "croix", "crone", "crony", "crook", "croon", "crop", "cross", "crow", "crowd", "crown", "crt", "crud", "crude", "cruel", "crumb", "crump", "crush", "crust", "crux", "cruz", "cry", "crypt", "cub", "cuba", "cube", "cubic", "cud", "cuddle", "cue", "cuff", "cull", "culpa", "cult", "cumin", "cuny", "cup", "cupful", "cupid", "cur", "curb", "curd", "cure", "curfew", "curia", "curie", "curio", "curl", "curry", "curse", "curt", "curve", "cusp", "cut", "cute", "cutlet", "cycad", "cycle", "cynic", "cyril", "cyrus", "cyst", "czar", "czech", "dab", "dacca", "dactyl", "dad", "dada", "daddy", "dade", "daffy", "dahl", "dahlia", "dairy", "dais", "daisy", "dakar", "dale", "daley", "dally", "daly", "dam", "dame", "damn", "damon", "damp", "damsel", "dan", "dana", "dance", "dandy", "dane", "dang", "dank", "danny", "dante", "dar", "dare", "dark", "darken", "darn", "darry", "dart", "dash", "data", "date", "dater", "datum", "daub", "daunt", "dave", "david", "davis", "davit", "davy", "dawn", "dawson", "day", "daze", "ddd", "dddd", "deacon", "dead", "deaf", "deal", "dealt", "dean", "deane", "dear", "death", "debar", "debby", "debit", "debra", "debris", "debt", "debug", "debut", "dec", "decal", "decay", "decca", "deck", "decker", "decor", "decree", "decry", "dee", "deed", "deem", "deep", "deer", "deere", "def", "defer", "deform", "deft", "defy", "degas", "degum", "deify", "deign", "deity", "deja", "del", "delay", "delft", "delhi", "delia", "dell", "della", "delta", "delve", "demark", "demit", "demon", "demur", "den", "deneb", "denial", "denny", "dense", "dent", "denton", "deny", "depot", "depth", "depute", "derby", "derek", "des", "desist", "desk", "detach", "deter", "deuce", "deus", "devil", "devoid", "devon", "dew", "dewar", "dewey", "dewy", "dey", "dhabi", "dial", "diana", "diane", "diary", "dibble", "dice", "dick", "dicta", "did", "dido", "die", "died", "diego", "diem", "diesel", "diet", "diety", "dietz", "dig", "digit", "dilate", "dill", "dim", "dime", "din", "dinah", "dine", "ding", "dingo", "dingy", "dint", "diode", "dip", "dirac", "dire", "dirge", "dirt", "dirty", "dis", "disc", "dish", "disk", "disney", "ditch", "ditto", "ditty", "diva", "divan", "dive", "dixie", "dixon", "dizzy", "dna", "dobbs", "dobson", "dock", "docket", "dod", "dodd", "dodge", "dodo", "doe", "doff", "dog", "doge", "dogma", "dolan", "dolce", "dole", "doll", "dolly", "dolt", "dome", "don", "done", "doneck", "donna", "donor", "doom", "door", "dope", "dora", "doria", "doric", "doris", "dose", "dot", "dote", "double", "doubt", "douce", "doug", "dough", "dour", "douse", "dove", "dow", "dowel", "down", "downs", "dowry", "doyle", "doze", "dozen", "drab", "draco", "draft", "drag", "drain", "drake", "dram", "drama", "drank", "drape", "draw", "drawl", "drawn", "dread", "dream", "dreamy", "dreg", "dress", "dressy", "drew", "drib", "dried", "drier", "drift", "drill", "drink", "drip", "drive", "droll", "drone", "drool", "droop", "drop", "dross", "drove", "drown", "drub", "drug", "druid", "drum", "drunk", "drury", "dry", "dryad", "dual", "duane", "dub", "dubhe", "dublin", "ducat", "duck", "duct", "dud", "due", "duel", "duet", "duff", "duffy", "dug", "dugan", "duke", "dull", "dully", "dulse", "duly", "duma", "dumb", "dummy", "dump", "dumpy", "dun", "dunce", "dune", "dung", "dunham", "dunk", "dunlop", "dunn", "dupe", "durer", "dusk", "dusky", "dust", "dusty", "dutch", "duty", "dwarf", "dwell", "dwelt", "dwight", "dwyer", "dyad", "dye", "dyer", "dying", "dyke", "dylan", "dyne", "each", "eagan", "eager", "eagle", "ear", "earl", "earn", "earth", "ease", "easel", "east", "easy", "eat", "eaten", "eater", "eaton", "eave", "ebb", "eben", "ebony", "echo", "eclat", "ecole", "eddie", "eddy", "eden", "edgar", "edge", "edgy", "edict", "edify", "edit", "edith", "editor", "edna", "edt", "edwin", "eee", "eeee", "eel", "eeoc", "eerie", "efface", "effie", "efg", "eft", "egan", "egg", "ego", "egress", "egret", "egypt", "eider", "eight", "eire", "eject", "eke", "elan", "elate", "elba", "elbow", "elder", "eldon", "elect", "elegy", "elena", "eleven", "elfin", "elgin", "eli", "elide", "eliot", "elite", "elk", "ell", "ella", "ellen", "ellis", "elm", "elmer", "elope", "else", "elsie", "elton", "elude", "elute", "elves", "ely", "embalm", "embark", "embed", "ember", "emcee", "emery", "emil", "emile", "emily", "emit", "emma", "emory", "empty", "enact", "enamel", "end", "endow", "enemy", "eng", "engel", "engle", "engulf", "enid", "enjoy", "enmity", "enoch", "enol", "enos", "enrico", "ensue", "enter", "entrap", "entry", "envoy", "envy", "epa", "epic", "epoch", "epoxy", "epsom", "equal", "equip", "era", "erase", "erato", "erda", "ere", "erect", "erg", "eric", "erich", "erie", "erik", "ernest", "ernie", "ernst", "erode", "eros", "err", "errand", "errol", "error", "erupt", "ervin", "erwin", "essay", "essen", "essex", "est", "ester", "estes", "estop", "eta", "etc", "etch", "ethan", "ethel", "ether", "ethic", "ethos", "ethyl", "etude", "eucre", "euler", "eureka", "eva", "evade", "evans", "eve", "even", "event", "every", "evict", "evil", "evoke", "evolve", "ewe", "ewing", "exact", "exalt", "exam", "excel", "excess", "exert", "exile", "exist", "exit", "exodus", "expel", "extant", "extent", "extol", "extra", "exude", "exult", "exxon", "eye", "eyed", "ezra", "faa", "faber", "fable", "face", "facet", "facile", "fact", "facto", "fad", "fade", "faery", "fag", "fahey", "fail", "fain", "faint", "fair", "fairy", "faith", "fake", "fall", "false", "fame", "fan", "fancy", "fang", "fanny", "fanout", "far", "farad", "farce", "fare", "fargo", "farley", "farm", "faro", "fast", "fat", "fatal", "fate", "fatty", "fault", "faun", "fauna", "faust", "fawn", "fay", "faze", "fbi", "fcc", "fda", "fear", "feast", "feat", "feb", "fed", "fee", "feed", "feel", "feet", "feign", "feint", "felice", "felix", "fell", "felon", "felt", "femur", "fence", "fend", "fermi", "fern", "ferric", "ferry", "fest", "fetal", "fetch", "fete", "fetid", "fetus", "feud", "fever", "few", "fff", "ffff", "fgh", "fiat", "fib", "fibrin", "fiche", "fide", "fief", "field", "fiend", "fiery", "fife", "fifo", "fifth", "fifty", "fig", "fight", "filch", "file", "filet", "fill", "filler", "filly", "film", "filmy", "filth", "fin", "final", "finale", "finch", "find", "fine", "finite", "fink", "finn", "finny", "fir", "fire", "firm", "first", "fish", "fishy", "fisk", "fiske", "fist", "fit", "fitch", "five", "fix", "fjord", "flack", "flag", "flail", "flair", "flak", "flake", "flaky", "flam", "flame", "flank", "flap", "flare", "flash", "flask", "flat", "flatus", "flaw", "flax", "flea", "fleck", "fled", "flee", "fleet", "flesh", "flew", "flex", "flick", "flier", "flinch", "fling", "flint", "flip", "flirt", "flit", "flo", "float", "floc", "flock", "floe", "flog", "flood", "floor", "flop", "floppy", "flora", "flour", "flout", "flow", "flown", "floyd", "flu", "flub", "flue", "fluff", "fluid", "fluke", "flung", "flush", "flute", "flux", "fly", "flyer", "flynn", "fmc", "foal", "foam", "foamy", "fob", "focal", "foci", "focus", "fodder", "foe", "fog", "foggy", "fogy", "foil", "foist", "fold", "foley", "folio", "folk", "folly", "fond", "font", "food", "fool", "foot", "foote", "fop", "for", "foray", "force", "ford", "fore", "forge", "forgot", "fork", "form", "fort", "forte", "forth", "forty", "forum", "foss", "fossil", "foul", "found", "fount", "four", "fovea", "fowl", "fox", "foxy", "foyer", "fpc", "frail", "frame", "fran", "franc", "franca", "frank", "franz", "frau", "fraud", "fray", "freak", "fred", "free", "freed", "freer", "frenzy", "freon", "fresh", "fret", "freud", "frey", "freya", "friar", "frick", "fried", "frill", "frilly", "frisky", "fritz", "fro", "frock", "frog", "from", "front", "frost", "froth", "frown", "froze", "fruit", "fry", "frye", "ftc", "fuchs", "fudge", "fuel", "fugal", "fugue", "fuji", "full", "fully", "fum", "fume", "fun", "fund", "fungal", "fungi", "funk", "funny", "fur", "furl", "furry", "fury", "furze", "fuse", "fuss", "fussy", "fusty", "fuzz", "fuzzy", "gab", "gable", "gabon", "gad", "gadget", "gaff", "gaffe", "gag", "gage", "gail", "gain", "gait", "gal", "gala", "galaxy", "gale", "galen", "gall", "gallop", "galt", "gam", "game", "gamin", "gamma", "gamut", "gander", "gang", "gao", "gap", "gape", "gar", "garb", "garish", "garner", "garry", "garth", "gary", "gas", "gash", "gasp", "gassy", "gate", "gates", "gator", "gauche", "gaudy", "gauge", "gaul", "gaunt", "gaur", "gauss", "gauze", "gave", "gavel", "gavin", "gawk", "gawky", "gay", "gaze", "gear", "gecko", "gee", "geese", "geigy", "gel", "geld", "gem", "gemma", "gene", "genie", "genii", "genoa", "genre", "gent", "gentry", "genus", "gerbil", "germ", "gerry", "get", "getty", "ggg", "gggg", "ghana", "ghent", "ghetto", "ghi", "ghost", "ghoul", "giant", "gibbs", "gibby", "gibe", "giddy", "gift", "gig", "gil", "gila", "gild", "giles", "gill", "gilt", "gimbal", "gimpy", "gin", "gina", "ginn", "gino", "gird", "girl", "girth", "gist", "give", "given", "glad", "gladdy", "glade", "glamor", "gland", "glans", "glare", "glass", "glaze", "gleam", "glean", "glee", "glen", "glenn", "glib", "glide", "glint", "gloat", "glob", "globe", "glom", "gloom", "glory", "gloss", "glove", "glow", "glue", "glued", "gluey", "gluing", "glum", "glut", "glyph", "gmt", "gnarl", "gnash", "gnat", "gnaw", "gnome", "gnp", "gnu", "goa", "goad", "goal", "goat", "gob", "goer", "goes", "goff", "gog", "goggle", "gogh", "gogo", "gold", "golf", "golly", "gone", "gong", "goo", "good", "goode", "goody", "goof", "goofy", "goose", "gop", "gordon", "gore", "goren", "gorge", "gorky", "gorse", "gory", "gosh", "gospel", "got", "gouda", "gouge", "gould", "gourd", "gout", "gown", "gpo", "grab", "grace", "grad", "grade", "grady", "graff", "graft", "grail", "grain", "grand", "grant", "grape", "graph", "grasp", "grass", "grata", "grate", "grater", "grave", "gravy", "gray", "graze", "great", "grebe", "greed", "greedy", "greek", "green", "greer", "greet", "greg", "gregg", "greta", "grew", "grey", "grid", "grief", "grieve", "grill", "grim", "grime", "grimm", "grin", "grind", "grip", "gripe", "grist", "grit", "groan", "groat", "groin", "groom", "grope", "gross", "groton", "group", "grout", "grove", "grow", "growl", "grown", "grub", "gruff", "grunt", "gsa", "guam", "guano", "guard", "guess", "guest", "guide", "guild", "guile", "guilt", "guise", "guitar", "gules", "gulf", "gull", "gully", "gulp", "gum", "gumbo", "gummy", "gun", "gunk", "gunky", "gunny", "gurgle", "guru", "gus", "gush", "gust", "gusto", "gusty", "gut", "gutsy", "guy", "guyana", "gwen", "gwyn", "gym", "gyp", "gypsy", "gyro", "haag", "haas", "habib", "habit", "hack", "had", "hades", "hadron", "hagen", "hager", "hague", "hahn", "haifa", "haiku", "hail", "hair", "hairy", "haiti", "hal", "hale", "haley", "half", "hall", "halma", "halo", "halt", "halvah", "halve", "ham", "hamal", "hamlin", "han", "hand", "handy", "haney", "hang", "hank", "hanna", "hanoi", "hans", "hansel", "hap", "happy", "hard", "hardy", "hare", "harem", "hark", "harley", "harm", "harp", "harpy", "harry", "harsh", "hart", "harvey", "hash", "hasp", "hast", "haste", "hasty", "hat", "hatch", "hate", "hater", "hath", "hatred", "haul", "haunt", "have", "haven", "havoc", "haw", "hawk", "hay", "haydn", "hayes", "hays", "hazard", "haze", "hazel", "hazy", "head", "heady", "heal", "healy", "heap", "hear", "heard", "heart", "heat", "heath", "heave", "heavy", "hebe", "hebrew", "heck", "heckle", "hedge", "heed", "heel", "heft", "hefty", "heigh", "heine", "heinz", "heir", "held", "helen", "helga", "helix", "hell", "hello", "helm", "helmut", "help", "hem", "hemp", "hen", "hence", "henri", "henry", "her", "hera", "herb", "herd", "here", "hero", "heroic", "heron", "herr", "hertz", "hess", "hesse", "hettie", "hetty", "hew", "hewitt", "hewn", "hex", "hey", "hhh", "hhhh", "hiatt", "hick", "hicks", "hid", "hide", "high", "hij", "hike", "hill", "hilly", "hilt", "hilum", "him", "hind", "hindu", "hines", "hinge", "hint", "hip", "hippo", "hippy", "hiram", "hire", "hirsch", "his", "hiss", "hit", "hitch", "hive", "hoagy", "hoar", "hoard", "hob", "hobbs", "hobby", "hobo", "hoc", "hock", "hodge", "hodges", "hoe", "hoff", "hog", "hogan", "hoi", "hokan", "hold", "holdup", "hole", "holly", "holm", "holst", "holt", "home", "homo", "honda", "hondo", "hone", "honey", "hong", "honk", "hooch", "hood", "hoof", "hook", "hookup", "hoop", "hoot", "hop", "hope", "horde", "horn", "horny", "horse", "horus", "hose", "host", "hot", "hotbox", "hotel", "hough", "hound", "hour", "house", "hove", "hovel", "hover", "how", "howdy", "howe", "howl", "hoy", "hoyt", "hub", "hubbub", "hubby", "huber", "huck", "hue", "hued", "huff", "hug", "huge", "hugh", "hughes", "hugo", "huh", "hulk", "hull", "hum", "human", "humid", "hump", "humus", "hun", "hunch", "hung", "hunk", "hunt", "hurd", "hurl", "huron", "hurrah", "hurry", "hurst", "hurt", "hurty", "hush", "husky", "hut", "hutch", "hyde", "hydra", "hydro", "hyena", "hying", "hyman", "hymen", "hymn", "hymnal", "iambic", "ian", "ibex", "ibid", "ibis", "ibm", "ibn", "icc", "ice", "icing", "icky", "icon", "icy", "ida", "idaho", "idea", "ideal", "idiom", "idiot", "idle", "idol", "idyll", "ieee", "iffy", "ifni", "igloo", "igor", "iii", "iiii", "ijk", "ike", "ileum", "iliac", "iliad", "ill", "illume", "ilona", "image", "imbue", "imp", "impel", "import", "impute", "inane", "inapt", "inc", "inca", "incest", "inch", "incur", "index", "india", "indies", "indy", "inept", "inert", "infect", "infer", "infima", "infix", "infra", "ingot", "inhere", "injun", "ink", "inlay", "inlet", "inman", "inn", "inner", "input", "insect", "inset", "insult", "intend", "inter", "into", "inure", "invoke", "ion", "ionic", "iota", "iowa", "ipso", "ira", "iran", "iraq", "irate", "ire", "irene", "iris", "irish", "irk", "irma", "iron", "irony", "irs", "irvin", "irwin", "isaac", "isabel", "ising", "isis", "islam", "island", "isle", "israel", "issue", "italy", "itch", "item", "ito", "itt", "ivan", "ive", "ivory", "ivy", "jab", "jack", "jacky", "jacm", "jacob", "jacobi", "jade", "jag", "jail", "jaime", "jake", "jam", "james", "jan", "jane", "janet", "janos", "janus", "japan", "jar", "jason", "java", "jaw", "jay", "jazz", "jazzy", "jean", "jed", "jeep", "jeff", "jejune", "jelly", "jenny", "jeres", "jerk", "jerky", "jerry", "jersey", "jess", "jesse", "jest", "jesus", "jet", "jew", "jewel", "jewett", "jewish", "jibe", "jiffy", "jig", "jill", "jilt", "jim", "jimmy", "jinx", "jive", "jjj", "jjjj", "jkl", "joan", "job", "jock", "jockey", "joe", "joel", "joey", "jog", "john", "johns", "join", "joint", "joke", "jolla", "jolly", "jolt", "jon", "jonas", "jones", "jorge", "jose", "josef", "joshua", "joss", "jostle", "jot", "joule", "joust", "jove", "jowl", "jowly", "joy", "joyce", "juan", "judas", "judd", "jude", "judge", "judo", "judy", "jug", "juggle", "juice", "juicy", "juju", "juke", "jukes", "julep", "jules", "julia", "julie", "julio", "july", "jumbo", "jump", "jumpy", "junco", "june", "junk", "junky", "juno", "junta", "jura", "jure", "juror", "jury", "just", "jut", "jute", "kabul", "kafka", "kahn", "kajar", "kale", "kalmia", "kane", "kant", "kapok", "kappa", "karate", "karen", "karl", "karma", "karol", "karp", "kate", "kathy", "katie", "katz", "kava", "kay", "kayo", "kazoo", "keats", "keel", "keen", "keep", "keg", "keith", "keller", "kelly", "kelp", "kemp", "ken", "keno", "kent", "kenya", "kepler", "kept", "kern", "kerr", "kerry", "ketch", "kevin", "key", "keyed", "keyes", "keys", "khaki", "khan", "khmer", "kick", "kid", "kidde", "kidney", "kiev", "kigali", "kill", "kim", "kin", "kind", "king", "kink", "kinky", "kiosk", "kiowa", "kirby", "kirk", "kirov", "kiss", "kit", "kite", "kitty", "kiva", "kivu", "kiwi", "kkk", "kkkk", "klan", "klaus", "klein", "kline", "klm", "klux", "knack", "knapp", "knauer", "knead", "knee", "kneel", "knelt", "knew", "knick", "knife", "knit", "knob", "knock", "knoll", "knot", "knott", "know", "known", "knox", "knurl", "koala", "koch", "kodak", "kola", "kombu", "kong", "koran", "korea", "kraft", "krause", "kraut", "krebs", "kruse", "kudo", "kudzu", "kuhn", "kulak", "kurd", "kurt", "kyle", "kyoto", "lab", "laban", "label", "labia", "labile", "lac", "lace", "lack", "lacy", "lad", "laden", "ladle", "lady", "lag", "lager", "lagoon", "lagos", "laid", "lain", "lair", "laity", "lake", "lam", "lamar", "lamb", "lame", "lamp", "lana", "lance", "land", "lane", "lang", "lange", "lanka", "lanky", "lao", "laos", "lap", "lapel", "lapse", "larch", "lard", "lares", "large", "lark", "larkin", "larry", "lars", "larva", "lase", "lash", "lass", "lasso", "last", "latch", "late", "later", "latest", "latex", "lath", "lathe", "latin", "latus", "laud", "laue", "laugh", "launch", "laura", "lava", "law", "lawn", "lawson", "lax", "lay", "layup", "laze", "lazy", "lea", "leach", "lead", "leaf", "leafy", "leak", "leaky", "lean", "leap", "leapt", "lear", "learn", "lease", "leash", "least", "leave", "led", "ledge", "lee", "leech", "leeds", "leek", "leer", "leery", "leeway", "left", "lefty", "leg", "legal", "leggy", "legion", "leigh", "leila", "leland", "lemma", "lemon", "len", "lena", "lend", "lenin", "lenny", "lens", "lent", "leo", "leon", "leona", "leone", "leper", "leroy", "less", "lessee", "lest", "let", "lethe", "lev", "levee", "level", "lever", "levi", "levin", "levis", "levy", "lew", "lewd", "lewis", "leyden", "liar", "libel", "libido", "libya", "lice", "lick", "lid", "lie", "lied", "lien", "lieu", "life", "lifo", "lift", "light", "like", "liken", "lila", "lilac", "lilly", "lilt", "lily", "lima", "limb", "limbo", "lime", "limit", "limp", "lin", "lind", "linda", "linden", "line", "linen", "lingo", "link", "lint", "linus", "lion", "lip", "lipid", "lisa", "lise", "lisle", "lisp", "list", "listen", "lit", "lithe", "litton", "live", "liven", "livid", "livre", "liz", "lizzie", "lll", "llll", "lloyd", "lmn", "load", "loaf", "loam", "loamy", "loan", "loath", "lob", "lobar", "lobby", "lobe", "lobo", "local", "loci", "lock", "locke", "locus", "lodge", "loeb", "loess", "loft", "lofty", "log", "logan", "loge", "logic", "loin", "loire", "lois", "loiter", "loki", "lola", "loll", "lolly", "lomb", "lome", "lone", "long", "look", "loom", "loon", "loop", "loose", "loot", "lop", "lope", "lopez", "lord", "lore", "loren", "los", "lose", "loss", "lossy", "lost", "lot", "lotte", "lotus", "lou", "loud", "louis", "louise", "louse", "lousy", "louver", "love", "low", "lowe", "lower", "lowry", "loy", "loyal", "lsi", "ltv", "lucas", "lucia", "lucid", "luck", "lucky", "lucre", "lucy", "lug", "luge", "luger", "luis", "luke", "lull", "lulu", "lumbar", "lumen", "lump", "lumpy", "lunar", "lunch", "lund", "lung", "lunge", "lura", "lurch", "lure", "lurid", "lurk", "lush", "lust", "lusty", "lute", "lutz", "lux", "luxe", "luzon", "lydia", "lye", "lying", "lykes", "lyle", "lyman", "lymph", "lynch", "lynn", "lynx", "lyon", "lyons", "lyra", "lyric", "mabel", "mac", "mace", "mach", "macho", "mack", "mackey", "macon", "macro", "mad", "madam", "made", "madman", "madsen", "mae", "magi", "magic", "magma", "magna", "magog", "maid", "maier", "mail", "maim", "main", "maine", "major", "make", "malady", "malay", "male", "mali", "mall", "malt", "malta", "mambo", "mamma", "mammal", "man", "mana", "manama", "mane", "mange", "mania", "manic", "mann", "manna", "manor", "mans", "manse", "mantle", "many", "mao", "maori", "map", "maple", "mar", "marc", "march", "marco", "marcy", "mardi", "mare", "margo", "maria", "marie", "marin", "marine", "mario", "mark", "marks", "marlin", "marrow", "marry", "mars", "marsh", "mart", "marty", "marx", "mary", "maser", "mash", "mask", "mason", "masque", "mass", "mast", "mat", "match", "mate", "mateo", "mater", "math", "matte", "maul", "mauve", "mavis", "maw", "mawr", "max", "maxim", "maxima", "may", "maya", "maybe", "mayer", "mayhem", "mayo", "mayor", "mayst", "mazda", "maze", "mba", "mccoy", "mcgee", "mckay", "mckee", "mcleod", "mead", "meal", "mealy", "mean", "meant", "meat", "meaty", "mecca", "mecum", "medal", "medea", "media", "medic", "medley", "meek", "meet", "meg", "mega", "meier", "meir", "mel", "meld", "melee", "mellow", "melon", "melt", "memo", "memoir", "men", "mend", "menlo", "menu", "merck", "mercy", "mere", "merge", "merit", "merle", "merry", "mesa", "mescal", "mesh", "meson", "mess", "messy", "met", "metal", "mete", "meter", "metro", "mew", "meyer", "meyers", "mezzo", "miami", "mica", "mice", "mickey", "micky", "micro", "mid", "midas", "midge", "midst", "mien", "miff", "mig", "might", "mike", "mila", "milan", "milch", "mild", "mildew", "mile", "miles", "milk", "milky", "mill", "mills", "milt", "mimi", "mimic", "mince", "mind", "mine", "mini", "minim", "mink", "minnow", "minor", "minos", "minot", "minsk", "mint", "minus", "mira", "mirage", "mire", "mirth", "miser", "misery", "miss", "missy", "mist", "misty", "mit", "mite", "mitre", "mitt", "mix", "mixup", "mizar", "mmm", "mmmm", "mno", "moan", "moat", "mob", "mobil", "mock", "modal", "mode", "model", "modem", "modish", "moe", "moen", "mohr", "moire", "moist", "molal", "molar", "mold", "mole", "moll", "mollie", "molly", "molt", "molten", "mommy", "mona", "monad", "mondo", "monel", "money", "monic", "monk", "mont", "monte", "month", "monty", "moo", "mood", "moody", "moon", "moor", "moore", "moose", "moot", "mop", "moral", "morale", "moran", "more", "morel", "morn", "moron", "morse", "morsel", "mort", "mosaic", "moser", "moses", "moss", "mossy", "most", "mot", "motel", "motet", "moth", "mother", "motif", "motor", "motto", "mould", "mound", "mount", "mourn", "mouse", "mousy", "mouth", "move", "movie", "mow", "moyer", "mph", "mrs", "much", "muck", "mucus", "mud", "mudd", "muddy", "muff", "muffin", "mug", "muggy", "mugho", "muir", "mulch", "mulct", "mule", "mull", "multi", "mum", "mummy", "munch", "mung", "munson", "muon", "muong", "mural", "muriel", "murk", "murky", "murre", "muse", "mush", "mushy", "music", "musk", "muslim", "must", "musty", "mute", "mutt", "muzak", "muzo", "myel", "myers", "mylar", "mynah", "myopia", "myra", "myron", "myrrh", "myself", "myth", "naacp", "nab", "nadir", "nag", "nagoya", "nagy", "naiad", "nail", "nair", "naive", "naked", "name", "nan", "nancy", "naomi", "nap", "nary", "nasa", "nasal", "nash", "nasty", "nat", "natal", "nate", "nato", "natty", "nature", "naval", "nave", "navel", "navy", "nay", "nazi", "nbc", "nbs", "ncaa", "ncr", "neal", "near", "neat", "neath", "neck", "ned", "nee", "need", "needy", "neff", "negate", "negro", "nehru", "neil", "nell", "nelsen", "neon", "nepal", "nero", "nerve", "ness", "nest", "net", "neuron", "neva", "neve", "new", "newel", "newt", "next", "nib", "nibs", "nice", "nicety", "niche", "nick", "niece", "niger", "nigh", "night", "nih", "nikko", "nil", "nile", "nimbus", "nimh", "nina", "nine", "ninth", "niobe", "nip", "nit", "nitric", "nitty", "nixon", "nnn", "nnnn", "noaa", "noah", "nob", "nobel", "noble", "nod", "nodal", "node", "noel", "noise", "noisy", "nolan", "noll", "nolo", "nomad", "non", "nonce", "none", "nook", "noon", "noose", "nop", "nor", "nora", "norm", "norma", "north", "norway", "nose", "not", "notch", "note", "notre", "noun", "nov", "nova", "novak", "novel", "novo", "now", "nrc", "nsf", "ntis", "nuance", "nubia", "nuclei", "nude", "nudge", "null", "numb", "nun", "nurse", "nut", "nyc", "nylon", "nymph", "nyu", "oaf", "oak", "oaken", "oakley", "oar", "oases", "oasis", "oat", "oath", "obese", "obey", "objet", "oboe", "occur", "ocean", "oct", "octal", "octave", "octet", "odd", "ode", "odin", "odium", "off", "offal", "offend", "offer", "oft", "often", "ogden", "ogle", "ogre", "ohio", "ohm", "ohmic", "oil", "oily", "oint", "okay", "olaf", "olav", "old", "olden", "oldy", "olga", "olin", "olive", "olsen", "olson", "omaha", "oman", "omega", "omen", "omit", "once", "one", "onion", "only", "onset", "onto", "onus", "onward", "onyx", "ooo", "oooo", "ooze", "opal", "opec", "opel", "open", "opera", "opium", "opt", "optic", "opus", "oral", "orate", "orb", "orbit", "orchid", "ordain", "order", "ore", "organ", "orgy", "orin", "orion", "ornery", "orono", "orr", "osaka", "oscar", "osier", "oslo", "other", "otis", "ott", "otter", "otto", "ouch", "ought", "ounce", "our", "oust", "out", "ouvre", "ouzel", "ouzo", "ova", "oval", "ovary", "ovate", "oven", "over", "overt", "ovid", "owe", "owens", "owing", "owl", "owly", "own", "oxen", "oxeye", "oxide", "oxnard", "ozark", "ozone", "pablo", "pabst", "pace", "pack", "packet", "pact", "pad", "paddy", "padre", "paean", "pagan", "page", "paid", "pail", "pain", "paine", "paint", "pair", "pal", "pale", "pall", "palm", "palo", "palsy", "pam", "pampa", "pan", "panama", "panda", "pane", "panel", "pang", "panic", "pansy", "pant", "panty", "paoli", "pap", "papa", "papal", "papaw", "paper", "pappy", "papua", "par", "parch", "pardon", "pare", "pareto", "paris", "park", "parke", "parks", "parr", "parry", "parse", "part", "party", "pascal", "pasha", "paso", "pass", "passe", "past", "paste", "pasty", "pat", "patch", "pate", "pater", "path", "patio", "patsy", "patti", "patton", "patty", "paul", "paula", "pauli", "paulo", "pause", "pave", "paw", "pawn", "pax", "pay", "payday", "payne", "paz", "pbs", "pea", "peace", "peach", "peak", "peaky", "peal", "peale", "pear", "pearl", "pease", "peat", "pebble", "pecan", "peck", "pecos", "pedal", "pedro", "pee", "peed", "peek", "peel", "peep", "peepy", "peer", "peg", "peggy", "pelt", "pen", "penal", "pence", "pencil", "pend", "penh", "penn", "penna", "penny", "pent", "peony", "pep", "peppy", "pepsi", "per", "perch", "percy", "perez", "peril", "perk", "perky", "perle", "perry", "persia", "pert", "perth", "peru", "peruse", "pest", "peste", "pet", "petal", "pete", "peter", "petit", "petri", "petty", "pew", "pewee", "phage", "phase", "phd", "phenol", "phi", "phil", "phlox", "phon", "phone", "phony", "photo", "phyla", "physic", "piano", "pica", "pick", "pickup", "picky", "pie", "piece", "pier", "pierce", "piety", "pig", "piggy", "pike", "pile", "pill", "pilot", "pimp", "pin", "pinch", "pine", "ping", "pinion", "pink", "pint", "pinto", "pion", "piotr", "pious", "pip", "pipe", "piper", "pique", "pit", "pitch", "pith", "pithy", "pitney", "pitt", "pity", "pius", "pivot", "pixel", "pixy", "pizza", "place", "plague", "plaid", "plain", "plan", "plane", "plank", "plant", "plasm", "plat", "plate", "plato", "play", "playa", "plaza", "plea", "plead", "pleat", "pledge", "pliny", "plod", "plop", "plot", "plow", "pluck", "plug", "plum", "plumb", "plume", "plump", "plunk", "plus", "plush", "plushy", "pluto", "ply", "poach", "pobox", "pod", "podge", "podia", "poe", "poem", "poesy", "poet", "poetry", "pogo", "poi", "point", "poise", "poke", "pol", "polar", "pole", "police", "polio", "polis", "polk", "polka", "poll", "polo", "pomona", "pomp", "ponce", "pond", "pong", "pont", "pony", "pooch", "pooh", "pool", "poole", "poop", "poor", "pop", "pope", "poppy", "porch", "pore", "pork", "porous", "port", "porte", "portia", "porto", "pose", "posey", "posh", "posit", "posse", "post", "posy", "pot", "potts", "pouch", "pound", "pour", "pout", "pow", "powder", "power", "ppm", "ppp", "pppp", "pqr", "prado", "pram", "prank", "pratt", "pray", "preen", "prefix", "prep", "press", "prexy", "prey", "priam", "price", "prick", "pride", "prig", "prim", "prima", "prime", "primp", "prince", "print", "prior", "prism", "prissy", "privy", "prize", "pro", "probe", "prod", "prof", "prom", "prone", "prong", "proof", "prop", "propyl", "prose", "proud", "prove", "prow", "prowl", "proxy", "prune", "pry", "psalm", "psi", "psych", "pta", "pub", "puck", "puddly", "puerto", "puff", "puffy", "pug", "pugh", "puke", "pull", "pulp", "pulse", "puma", "pump", "pun", "punch", "punic", "punish", "punk", "punky", "punt", "puny", "pup", "pupal", "pupil", "puppy", "pure", "purge", "purl", "purr", "purse", "pus", "pusan", "pusey", "push", "pussy", "put", "putt", "putty", "pvc", "pygmy", "pyle", "pyre", "pyrex", "pyrite", "qatar", "qed", "qqq", "qqqq", "qrs", "qua", "quack", "quad", "quaff", "quail", "quake", "qualm", "quark", "quarry", "quart", "quash", "quasi", "quay", "queasy", "queen", "queer", "quell", "query", "quest", "queue", "quick", "quid", "quiet", "quill", "quilt", "quinn", "quint", "quip", "quirk", "quirt", "quit", "quite", "quito", "quiz", "quo", "quod", "quota", "quote", "rabat", "rabbi", "rabbit", "rabid", "rabin", "race", "rack", "racy", "radar", "radii", "radio", "radium", "radix", "radon", "rae", "rafael", "raft", "rag", "rage", "raid", "rail", "rain", "rainy", "raise", "raj", "rajah", "rake", "rally", "ralph", "ram", "raman", "ramo", "ramp", "ramsey", "ran", "ranch", "rand", "randy", "rang", "range", "rangy", "rank", "rant", "raoul", "rap", "rape", "rapid", "rapt", "rare", "rasa", "rascal", "rash", "rasp", "rat", "rata", "rate", "rater", "ratio", "rattle", "raul", "rave", "ravel", "raven", "raw", "ray", "raze", "razor", "rca", "reach", "read", "ready", "reagan", "real", "realm", "ream", "reap", "rear", "reave", "reb", "rebel", "rebut", "recipe", "reck", "recur", "red", "redeem", "reduce", "reed", "reedy", "reef", "reek", "reel", "reese", "reeve", "refer", "regal", "regina", "regis", "reich", "reid", "reign", "rein", "relax", "relay", "relic", "reman", "remedy", "remit", "remus", "rena", "renal", "rend", "rene", "renown", "rent", "rep", "repel", "repent", "resin", "resort", "rest", "ret", "retch", "return", "reub", "rev", "reveal", "revel", "rever", "revet", "revved", "rex", "rhea", "rheum", "rhine", "rhino", "rho", "rhoda", "rhode", "rhyme", "rib", "rica", "rice", "rich", "rick", "rico", "rid", "ride", "ridge", "rifle", "rift", "rig", "riga", "rigel", "riggs", "right", "rigid", "riley", "rill", "rilly", "rim", "rime", "rimy", "ring", "rink", "rinse", "rio", "riot", "rip", "ripe", "ripen", "ripley", "rise", "risen", "risk", "risky", "rite", "ritz", "rival", "riven", "river", "rivet", "riyadh", "roach", "road", "roam", "roar", "roast", "rob", "robe", "robin", "robot", "rock", "rocket", "rocky", "rod", "rode", "rodeo", "roe", "roger", "rogue", "roil", "role", "roll", "roman", "rome", "romeo", "romp", "ron", "rondo", "rood", "roof", "rook", "rookie", "rooky", "room", "roomy", "roost", "root", "rope", "rosa", "rose", "rosen", "ross", "rosy", "rot", "rotc", "roth", "rotor", "rouge", "rough", "round", "rouse", "rout", "route", "rove", "row", "rowdy", "rowe", "roy", "royal", "royce", "rpm", "rrr", "rrrr", "rst", "rsvp", "ruanda", "rub", "rube", "ruben", "rubin", "rubric", "ruby", "ruddy", "rude", "rudy", "rue", "rufus", "rug", "ruin", "rule", "rum", "rumen", "rummy", "rump", "rumpus", "run", "rune", "rung", "runge", "runic", "runt", "runty", "rupee", "rural", "ruse", "rush", "rusk", "russ", "russo", "rust", "rusty", "rut", "ruth", "rutty", "ryan", "ryder", "rye", "sabine", "sable", "sabra", "sac", "sachs", "sack", "sad", "saddle", "sadie", "safari", "safe", "sag", "saga", "sage", "sago", "said", "sail", "saint", "sake", "sal", "salad", "sale", "salem", "saline", "salk", "salle", "sally", "salon", "salt", "salty", "salve", "salvo", "sam", "samba", "same", "sammy", "samoa", "samuel", "san", "sana", "sand", "sandal", "sandy", "sane", "sang", "sank", "sans", "santa", "santo", "sao", "sap", "sappy", "sara", "sarah", "saran", "sari", "sash", "sat", "satan", "satin", "satyr", "sauce", "saucy", "saud", "saudi", "saul", "sault", "saute", "save", "savoy", "savvy", "saw", "sawyer", "sax", "saxon", "say", "scab", "scala", "scald", "scale", "scalp", "scam", "scamp", "scan", "scant", "scar", "scare", "scarf", "scary", "scat", "scaup", "scene", "scent", "school", "scion", "scm", "scoff", "scold", "scoop", "scoot", "scope", "scops", "score", "scoria", "scorn", "scot", "scott", "scour", "scout", "scowl", "scram", "scrap", "scrape", "screw", "scrim", "scrub", "scuba", "scud", "scuff", "scull", "scum", "scurry", "sea", "seal", "seam", "seamy", "sean", "sear", "sears", "season", "seat", "sec", "secant", "sect", "sedan", "seder", "sedge", "see", "seed", "seedy", "seek", "seem", "seen", "seep", "seethe", "seize", "self", "sell", "selma", "semi", "sen", "send", "seneca", "senor", "sense", "sent", "sentry", "seoul", "sepal", "sepia", "sepoy", "sept", "septa", "sequin", "sera", "serf", "serge", "serif", "serum", "serve", "servo", "set", "seth", "seton", "setup", "seven", "sever", "severe", "sew", "sewn", "sex", "sexy", "shack", "shad", "shade", "shady", "shafer", "shaft", "shag", "shah", "shake", "shaken", "shako", "shaky", "shale", "shall", "sham", "shame", "shank", "shape", "shard", "share", "shari", "shark", "sharp", "shave", "shaw", "shawl", "shay", "she", "shea", "sheaf", "shear", "sheath", "shed", "sheen", "sheep", "sheer", "sheet", "sheik", "shelf", "shell", "shied", "shift", "shill", "shim", "shin", "shine", "shinto", "shiny", "ship", "shire", "shirk", "shirt", "shish", "shiv", "shoal", "shock", "shod", "shoe", "shoji", "shone", "shoo", "shook", "shoot", "shop", "shore", "short", "shot", "shout", "shove", "show", "shown", "showy", "shrank", "shred", "shrew", "shrike", "shrub", "shrug", "shu", "shuck", "shun", "shunt", "shut", "shy", "sial", "siam", "sian", "sib", "sibley", "sibyl", "sic", "sick", "side", "sidle", "siege", "siena", "sieve", "sift", "sigh", "sight", "sigma", "sign", "signal", "signor", "silas", "silk", "silky", "sill", "silly", "silo", "silt", "silty", "sima", "simon", "simons", "sims", "sin", "sinai", "since", "sine", "sinew", "sing", "singe", "sinh", "sink", "sinus", "sioux", "sip", "sir", "sire", "siren", "sis", "sisal", "sit", "site", "situ", "situs", "siva", "six", "sixgun", "sixth", "sixty", "size", "skat", "skate", "skeet", "skew", "ski", "skid", "skied", "skiff", "skill", "skim", "skimp", "skimpy", "skin", "skip", "skirt", "skit", "skulk", "skull", "skunk", "sky", "skye", "slab", "slack", "slag", "slain", "slake", "slam", "slang", "slant", "slap", "slash", "slat", "slate", "slater", "slav", "slave", "slay", "sled", "sleek", "sleep", "sleet", "slept", "slew", "slice", "slick", "slid", "slide", "slim", "slime", "slimy", "sling", "slip", "slit", "sliver", "sloan", "slob", "sloe", "slog", "sloop", "slop", "slope", "slosh", "slot", "sloth", "slow", "slug", "sluice", "slum", "slump", "slung", "slur", "slurp", "sly", "smack", "small", "smart", "smash", "smear", "smell", "smelt", "smile", "smirk", "smith", "smithy", "smog", "smoke", "smoky", "smug", "smut", "snack", "snafu", "snag", "snail", "snake", "snap", "snare", "snark", "snarl", "snatch", "sneak", "sneer", "snell", "snick", "sniff", "snip", "snipe", "snob", "snook", "snoop", "snore", "snort", "snout", "snow", "snowy", "snub", "snuff", "snug", "soak", "soap", "soapy", "soar", "sob", "sober", "social", "sock", "sod", "soda", "sofa", "sofia", "soft", "soften", "soggy", "soil", "sol", "solar", "sold", "sole", "solemn", "solid", "solo", "solon", "solve", "soma", "somal", "some", "son", "sonar", "song", "sonic", "sonny", "sonora", "sony", "soon", "soot", "sooth", "sop", "sora", "sorb", "sore", "sorry", "sort", "sos", "sou", "sough", "soul", "sound", "soup", "sour", "source", "sousa", "south", "sow", "sown", "soy", "soya", "spa", "space", "spade", "spain", "span", "spar", "spare", "sparge", "spark", "spasm", "spat", "spate", "spawn", "spay", "speak", "spear", "spec", "speck", "sped", "speed", "spell", "spend", "spent", "sperm", "sperry", "spew", "spica", "spice", "spicy", "spike", "spiky", "spill", "spilt", "spin", "spine", "spiny", "spire", "spiro", "spit", "spite", "spitz", "splat", "splay", "spline", "split", "spoil", "spoke", "spoof", "spook", "spooky", "spool", "spoon", "spore", "sport", "spot", "spout", "sprain", "spray", "spree", "sprig", "spruce", "sprue", "spud", "spume", "spun", "spunk", "spur", "spurn", "spurt", "spy", "squad", "squat", "squaw", "squibb", "squid", "squint", "sri", "sss", "ssss", "sst", "st.", "stab", "stack", "stacy", "staff", "stag", "stage", "stagy", "stahl", "staid", "stain", "stair", "stake", "stale", "stalk", "stall", "stamp", "stan", "stance", "stand", "stank", "staph", "star", "stare", "stark", "starr", "start", "stash", "state", "statue", "stave", "stay", "stead", "steak", "steal", "steam", "steed", "steel", "steele", "steen", "steep", "steer", "stein", "stella", "stem", "step", "stern", "steve", "stew", "stick", "stiff", "stile", "still", "stilt", "sting", "stingy", "stink", "stint", "stir", "stock", "stoic", "stoke", "stole", "stomp", "stone", "stony", "stood", "stool", "stoop", "stop", "store", "storey", "stork", "storm", "story", "stout", "stove", "stow", "strafe", "strap", "straw", "stray", "strewn", "strip", "stroll", "strom", "strop", "strum", "strut", "stu", "stuart", "stub", "stuck", "stud", "study", "stuff", "stuffy", "stump", "stun", "stung", "stunk", "stunt", "sturm", "style", "styli", "styx", "suave", "sub", "subtly", "such", "suck", "sud", "sudan", "suds", "sue", "suey", "suez", "sugar", "suit", "suite", "sulfa", "sulk", "sulky", "sully", "sultry", "sum", "sumac", "summon", "sun", "sung", "sunk", "sunny", "sunset", "suny", "sup", "super", "supra", "sure", "surf", "surge", "sus", "susan", "sushi", "susie", "sutton", "swab", "swag", "swain", "swam", "swami", "swamp", "swampy", "swan", "swank", "swap", "swarm", "swart", "swat", "swath", "sway", "swear", "sweat", "sweaty", "swede", "sweep", "sweet", "swell", "swelt", "swept", "swift", "swig", "swim", "swine", "swing", "swipe", "swirl", "swish", "swiss", "swoop", "sword", "swore", "sworn", "swum", "swung", "sybil", "sykes", "sylow", "sylvan", "synge", "synod", "syria", "syrup", "tab", "table", "taboo", "tabu", "tabula", "tacit", "tack", "tacky", "tacoma", "tact", "tad", "taffy", "taft", "tag", "tahoe", "tail", "taint", "take", "taken", "talc", "tale", "talk", "talky", "tall", "tallow", "tally", "talon", "talus", "tam", "tame", "tamp", "tampa", "tan", "tang", "tango", "tangy", "tanh", "tank", "tansy", "tanya", "tao", "taos", "tap", "tapa", "tape", "taper", "tapir", "tapis", "tappa", "tar", "tara", "tardy", "tariff", "tarry", "tart", "task", "tass", "taste", "tasty", "tat", "tate", "tater", "tattle", "tatty", "tau", "taunt", "taut", "tavern", "tawny", "tax", "taxi", "tea", "teach", "teal", "team", "tear", "tease", "teat", "tech", "tecum", "ted", "teddy", "tee", "teem", "teen", "teensy", "teet", "teeth", "telex", "tell", "tempo", "tempt", "ten", "tend", "tenet", "tenney", "tenon", "tenor", "tense", "tensor", "tent", "tenth", "tepee", "tepid", "term", "tern", "terra", "terre", "terry", "terse", "tess", "test", "testy", "tete", "texan", "texas", "text", "thai", "than", "thank", "that", "thaw", "the", "thea", "thee", "theft", "their", "them", "theme", "then", "there", "these", "theta", "they", "thick", "thief", "thigh", "thin", "thine", "thing", "think", "third", "this", "thong", "thor", "thorn", "thorny", "those", "thou", "thread", "three", "threw", "throb", "throes", "throw", "thrum", "thud", "thug", "thule", "thumb", "thump", "thus", "thy", "thyme", "tiber", "tibet", "tibia", "tic", "tick", "ticket", "tid", "tidal", "tidbit", "tide", "tidy", "tie", "tied", "tier", "tift", "tiger", "tight", "til", "tilde", "tile", "till", "tilt", "tilth", "tim", "time", "timex", "timid", "timon", "tin", "tina", "tine", "tinge", "tint", "tiny", "tioga", "tip", "tipoff", "tippy", "tipsy", "tire", "tit", "titan", "tithe", "title", "titus", "tnt", "toad", "toady", "toast", "toby", "today", "todd", "toe", "tofu", "tog", "togo", "togs", "toil", "toilet", "token", "tokyo", "told", "toll", "tom", "tomb", "tome", "tommy", "ton", "tonal", "tone", "tong", "toni", "tonic", "tonk", "tonsil", "tony", "too", "took", "tool", "toot", "tooth", "top", "topaz", "topic", "topple", "topsy", "tor", "torah", "torch", "tore", "tori", "torn", "torr", "torso", "tort", "torus", "tory", "toss", "tot", "total", "tote", "totem", "touch", "tough", "tour", "tout", "tow", "towel", "tower", "town", "toxic", "toxin", "toy", "trace", "track", "tract", "tracy", "trade", "trag", "trail", "train", "trait", "tram", "tramp", "trap", "trash", "trawl", "tread", "treat", "treble", "tree", "trek", "trench", "trend", "tress", "triad", "trial", "tribe", "trick", "tried", "trig", "trill", "trim", "trio", "trip", "tripe", "trite", "triton", "trod", "troll", "troop", "trot", "trout", "troy", "truce", "truck", "trudge", "trudy", "true", "truly", "trump", "trunk", "truss", "trust", "truth", "trw", "try", "tsar", "ttl", "ttt", "tttt", "tty", "tub", "tuba", "tube", "tuck", "tudor", "tuff", "tuft", "tug", "tulane", "tulip", "tulle", "tulsa", "tum", "tun", "tuna", "tune", "tung", "tunic", "tunis", "tunnel", "tuple", "turf", "turin", "turk", "turn", "turvy", "tusk", "tussle", "tutor", "tutu", "tuv", "tva", "twa", "twain", "tweak", "tweed", "twice", "twig", "twill", "twin", "twine", "twirl", "twist", "twisty", "twit", "two", "twx", "tyburn", "tying", "tyler", "type", "typic", "typo", "tyson", "ucla", "ugh", "ugly", "ulan", "ulcer", "ultra", "umber", "umbra", "umpire", "unary", "uncle", "under", "unify", "union", "unit", "unite", "unity", "unix", "until", "upend", "uphold", "upon", "upper", "uproar", "upset", "uptake", "upton", "urban", "urbane", "urea", "urge", "uri", "urine", "uris", "urn", "ursa", "usa", "usaf", "usage", "usc", "usda", "use", "useful", "usgs", "usher", "usia", "usn", "usps", "ussr", "usual", "usurp", "usury", "utah", "utica", "utile", "utmost", "utter", "uuu", "uuuu", "uvw", "vacua", "vacuo", "vade", "vaduz", "vague", "vail", "vain", "vale", "valet", "valeur", "valid", "value", "valve", "vamp", "van", "vance", "vane", "vary", "vase", "vast", "vat", "vault", "veal", "veda", "vee", "veer", "veery", "vega", "veil", "vein", "velar", "veldt", "vella", "vellum", "venal", "vend", "venial", "venom", "vent", "venus", "vera", "verb", "verde", "verdi", "verge", "verity", "verna", "verne", "versa", "verse", "verve", "very", "vessel", "vest", "vet", "vetch", "veto", "vex", "via", "vial", "vicar", "vice", "vichy", "vicky", "vida", "video", "vie", "viet", "view", "vigil", "vii", "viii", "vile", "villa", "vine", "vinyl", "viola", "violet", "virgil", "virgo", "virus", "vis", "visa", "vise", "visit", "visor", "vista", "vita", "vitae", "vital", "vito", "vitro", "viva", "vivian", "vivid", "vivo", "vixen", "viz", "vocal", "vogel", "vogue", "voice", "void", "volt", "volta", "volvo", "vomit", "von", "voss", "vote", "vouch", "vow", "vowel", "vulcan", "vvv", "vvvv", "vying", "waals", "wac", "wack", "wacke", "wacky", "waco", "wad", "wade", "wadi", "wafer", "wag", "wage", "waggle", "wah", "wahl", "wail", "waist", "wait", "waite", "waive", "wake", "waken", "waldo", "wale", "walk", "walkie", "wall", "walls", "wally", "walsh", "walt", "walton", "waltz", "wan", "wand", "wane", "wang", "want", "war", "ward", "ware", "warm", "warmth", "warn", "warp", "warren", "wart", "warty", "wary", "was", "wash", "washy", "wasp", "wast", "waste", "watch", "water", "watt", "watts", "wave", "wavy", "wax", "waxen", "waxy", "way", "wayne", "weak", "weal", "wealth", "wean", "wear", "weary", "weave", "web", "webb", "weber", "weco", "wed", "wedge", "wee", "weed", "weedy", "week", "weeks", "weep", "wehr", "wei", "weigh", "weir", "weird", "weiss", "welch", "weld", "well", "wells", "welsh", "welt", "wendy", "went", "wept", "were", "wert", "west", "wet", "whack", "whale", "wham", "wharf", "what", "wheat", "whee", "wheel", "whelk", "whelm", "whelp", "when", "where", "whet", "which", "whiff", "whig", "while", "whim", "whine", "whinny", "whip", "whir", "whirl", "whisk", "whit", "white", "whiz", "who", "whoa", "whole", "whom", "whoop", "whoosh", "whop", "whose", "whup", "why", "wick", "wide", "widen", "widow", "width", "wield", "wier", "wife", "wig", "wild", "wile", "wiley", "wilkes", "will", "willa", "wills", "wilma", "wilt", "wily", "win", "wince", "winch", "wind", "windy", "wine", "wing", "wink", "winnie", "wino", "winter", "winy", "wipe", "wire", "wiry", "wise", "wish", "wishy", "wisp", "wispy", "wit", "witch", "with", "withe", "withy", "witt", "witty", "wive", "woe", "wok", "woke", "wold", "wolf", "wolfe", "wolff", "wolve", "woman", "womb", "women", "won", "wonder", "wong", "wont", "woo", "wood", "woods", "woody", "wool", "woozy", "word", "wordy", "wore", "work", "world", "worm", "wormy", "worn", "worry", "worse", "worst", "worth", "wotan", "would", "wound", "wove", "woven", "wow", "wrack", "wrap", "wrath", "wreak", "wreck", "wrest", "wring", "wrist", "writ", "write", "writhe", "wrong", "wrote", "wry", "wuhan", "www", "wwww", "wxy", "wyatt", "wyeth", "wylie", "wyman", "wyner", "wynn", "xenon", "xerox", "xxx", "xxxx", "xylem", "xyz", "yacht", "yah", "yak", "yale", "yalta", "yam", "yamaha", "yang", "yank", "yap", "yaqui", "yard", "yarn", "yates", "yaw", "yawl", "yawn", "yea", "yeah", "year", "yearn", "yeast", "yeasty", "yeats", "yell", "yelp", "yemen", "yen", "yet", "yield", "yin", "yip", "ymca", "yodel", "yoder", "yoga", "yogi", "yoke", "yokel", "yolk", "yon", "yond", "yore", "york", "yost", "you", "young", "your", "youth", "yow", "yucca", "yuck", "yuh", "yuki", "yukon", "yule", "yves", "ywca", "yyy", "yyyy", "zag", "zaire", "zan", "zap", "zazen", "zeal", "zealot", "zebra", "zeiss", "zen", "zero", "zest", "zesty", "zeta", "zeus", "zig", "zilch", "zinc", "zing", "zion", "zip", "zloty", "zoe", "zomba", "zone", "zoo", "zoom", "zorn", "zurich", "zzz", "zzzz"]
true
true
f7278c9a625b2d1059e2cfccec2d387b369c5723
3,269
py
Python
test_src/Tests/test07_scroll_list/test_TC09.py
BJanos87/Vizsgaremek-conduit-app
1ffb309389b0cbe68aca56bfde50ba8b17219d03
[ "MIT" ]
null
null
null
test_src/Tests/test07_scroll_list/test_TC09.py
BJanos87/Vizsgaremek-conduit-app
1ffb309389b0cbe68aca56bfde50ba8b17219d03
[ "MIT" ]
null
null
null
test_src/Tests/test07_scroll_list/test_TC09.py
BJanos87/Vizsgaremek-conduit-app
1ffb309389b0cbe68aca56bfde50ba8b17219d03
[ "MIT" ]
null
null
null
from test_src.Tests.test07_scroll_list.conftest import PyFix from test_src.Pages.HomePage import HomePage from test_src.Pages.LoginPage import LoginPage from test_src.Pages.MainPage import MainPage from test_src.Data.test_data import TestData import time class TestScrollList(PyFix): """this used to check the title of the loaded url, and check the Sign In button""" def test_homepage(self): try: self.HomePage = HomePage(self.driver) assert self.HomePage.get_home_page_url() == TestData.BASE_URL assert self.HomePage.get_home_page_title() == TestData.HOME_PAGE_TITLE assert self.HomePage.is_sign_in_btn_displayed() is True self.HomePage.click_sign_in_btn() time.sleep(1) except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err)) """this used to check the elements of the Login Page""" """Login an existing user""" def test_check_login_form(self): try: self.LoginPage = LoginPage(self.driver) assert self.LoginPage.is_inputs_displayed() is True assert self.LoginPage.is_inputs_placeholder() is True assert self.LoginPage.is_password_type() is True except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err)) """this used to fill Login Page and sign in to app""" def test_login_exist_user(self): try: self.LoginPage = LoginPage(self.driver) self.LoginPage.fill_login_existed_email() assert self.LoginPage.is_sign_in_btn_displayed() is True self.LoginPage.click_sign_in_btn() time.sleep(3) except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err)) """this used to check scroll in the list""" def test_check_scroll_in_the_list(self): try: self.MainPage = MainPage(self.driver) assert self.MainPage.is_username_displayed() == TestData.reg_test_valid[0] assert self.MainPage.count_post_fields() == 11 self.MainPage.scroll_to_bottom_of_the_main_page() assert self.MainPage.is_next_btn_displayed() is True assert self.MainPage.is_next_btn_selected() is False self.MainPage.click_next_btn_topic_list() time.sleep(3) # assert self.MainPage.is_next_btn_selected() is True assert self.MainPage.count_post_fields() == 1 assert self.MainPage.is_log_out_btn_displayed() is True self.MainPage.click_log_out_btn() time.sleep(1) except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err)) """this used to check successful navigate to home page""" def test_homepage_is_displayed(self): try: self.HomePage = HomePage(self.driver) assert self.HomePage.get_home_page_url() == TestData.BASE_URL assert self.HomePage.get_home_page_title() == TestData.HOME_PAGE_TITLE assert self.HomePage.is_sign_in_btn_displayed() is True except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err))
44.780822
86
0.674824
from test_src.Tests.test07_scroll_list.conftest import PyFix from test_src.Pages.HomePage import HomePage from test_src.Pages.LoginPage import LoginPage from test_src.Pages.MainPage import MainPage from test_src.Data.test_data import TestData import time class TestScrollList(PyFix): def test_homepage(self): try: self.HomePage = HomePage(self.driver) assert self.HomePage.get_home_page_url() == TestData.BASE_URL assert self.HomePage.get_home_page_title() == TestData.HOME_PAGE_TITLE assert self.HomePage.is_sign_in_btn_displayed() is True self.HomePage.click_sign_in_btn() time.sleep(1) except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err)) def test_check_login_form(self): try: self.LoginPage = LoginPage(self.driver) assert self.LoginPage.is_inputs_displayed() is True assert self.LoginPage.is_inputs_placeholder() is True assert self.LoginPage.is_password_type() is True except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err)) def test_login_exist_user(self): try: self.LoginPage = LoginPage(self.driver) self.LoginPage.fill_login_existed_email() assert self.LoginPage.is_sign_in_btn_displayed() is True self.LoginPage.click_sign_in_btn() time.sleep(3) except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err)) def test_check_scroll_in_the_list(self): try: self.MainPage = MainPage(self.driver) assert self.MainPage.is_username_displayed() == TestData.reg_test_valid[0] assert self.MainPage.count_post_fields() == 11 self.MainPage.scroll_to_bottom_of_the_main_page() assert self.MainPage.is_next_btn_displayed() is True assert self.MainPage.is_next_btn_selected() is False self.MainPage.click_next_btn_topic_list() time.sleep(3) assert self.MainPage.count_post_fields() == 1 assert self.MainPage.is_log_out_btn_displayed() is True self.MainPage.click_log_out_btn() time.sleep(1) except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err)) def test_homepage_is_displayed(self): try: self.HomePage = HomePage(self.driver) assert self.HomePage.get_home_page_url() == TestData.BASE_URL assert self.HomePage.get_home_page_title() == TestData.HOME_PAGE_TITLE assert self.HomePage.is_sign_in_btn_displayed() is True except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err))
true
true
f7278cd33f1012970fa1eafccf108f1db2ee92aa
1,387
py
Python
python_code/vnev/Lib/site-packages/jdcloud_sdk/services/kubernetes/apis/SetAutoRepairRequest.py
Ureimu/weather-robot
7634195af388538a566ccea9f8a8534c5fb0f4b6
[ "MIT" ]
14
2018-04-19T09:53:56.000Z
2022-01-27T06:05:48.000Z
python_code/vnev/Lib/site-packages/jdcloud_sdk/services/kubernetes/apis/SetAutoRepairRequest.py
Ureimu/weather-robot
7634195af388538a566ccea9f8a8534c5fb0f4b6
[ "MIT" ]
15
2018-09-11T05:39:54.000Z
2021-07-02T12:38:02.000Z
python_code/vnev/Lib/site-packages/jdcloud_sdk/services/kubernetes/apis/SetAutoRepairRequest.py
Ureimu/weather-robot
7634195af388538a566ccea9f8a8534c5fb0f4b6
[ "MIT" ]
33
2018-04-20T05:29:16.000Z
2022-02-17T09:10:05.000Z
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # NOTE: This class is auto generated by the jdcloud code generator program. from jdcloud_sdk.core.jdcloudrequest import JDCloudRequest class SetAutoRepairRequest(JDCloudRequest): """ 设置工作节点组的自动修复 """ def __init__(self, parameters, header=None, version="v1"): super(SetAutoRepairRequest, self).__init__( '/regions/{regionId}/nodeGroups/{nodeGroupId}:setAutoRepair', 'POST', header, version) self.parameters = parameters class SetAutoRepairParameters(object): def __init__(self, regionId, nodeGroupId, enabled): """ :param regionId: 地域 ID :param nodeGroupId: 工作节点组 ID :param enabled: 是否开启自动修复 """ self.regionId = regionId self.nodeGroupId = nodeGroupId self.enabled = enabled
30.152174
98
0.708724
from jdcloud_sdk.core.jdcloudrequest import JDCloudRequest class SetAutoRepairRequest(JDCloudRequest): def __init__(self, parameters, header=None, version="v1"): super(SetAutoRepairRequest, self).__init__( '/regions/{regionId}/nodeGroups/{nodeGroupId}:setAutoRepair', 'POST', header, version) self.parameters = parameters class SetAutoRepairParameters(object): def __init__(self, regionId, nodeGroupId, enabled): self.regionId = regionId self.nodeGroupId = nodeGroupId self.enabled = enabled
true
true
f7278d74a416cfce5eaf0b1a81d51c2651746a7a
5,101
py
Python
logicmonitor_sdk/models/data_source_update_reasons_pagination_response.py
JeremyTangCD/lm-sdk-python
2a15e055e5a3f72d2f2e4fb43bdbed203c5a9983
[ "Apache-2.0" ]
null
null
null
logicmonitor_sdk/models/data_source_update_reasons_pagination_response.py
JeremyTangCD/lm-sdk-python
2a15e055e5a3f72d2f2e4fb43bdbed203c5a9983
[ "Apache-2.0" ]
null
null
null
logicmonitor_sdk/models/data_source_update_reasons_pagination_response.py
JeremyTangCD/lm-sdk-python
2a15e055e5a3f72d2f2e4fb43bdbed203c5a9983
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 """ LogicMonitor REST API LogicMonitor is a SaaS-based performance monitoring platform that provides full visibility into complex, hybrid infrastructures, offering granular performance monitoring and actionable data and insights. logicmonitor_sdk enables you to manage your LogicMonitor account programmatically. # noqa: E501 OpenAPI spec version: 1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from logicmonitor_sdk.models.update_reason import UpdateReason # noqa: F401,E501 class DataSourceUpdateReasonsPaginationResponse(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'total': 'int', 'search_id': 'str', 'items': 'list[UpdateReason]' } attribute_map = { 'total': 'total', 'search_id': 'searchId', 'items': 'items' } def __init__(self, total=None, search_id=None, items=None): # noqa: E501 """DataSourceUpdateReasonsPaginationResponse - a model defined in Swagger""" # noqa: E501 self._total = None self._search_id = None self._items = None self.discriminator = None if total is not None: self.total = total if search_id is not None: self.search_id = search_id if items is not None: self.items = items @property def total(self): """Gets the total of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :return: The total of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :rtype: int """ return self._total @total.setter def total(self, total): """Sets the total of this DataSourceUpdateReasonsPaginationResponse. :param total: The total of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :type: int """ self._total = total @property def search_id(self): """Gets the search_id of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :return: The search_id of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :rtype: str """ return self._search_id @search_id.setter def search_id(self, search_id): """Sets the search_id of this DataSourceUpdateReasonsPaginationResponse. :param search_id: The search_id of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :type: str """ self._search_id = search_id @property def items(self): """Gets the items of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :return: The items of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :rtype: list[UpdateReason] """ return self._items @items.setter def items(self, items): """Sets the items of this DataSourceUpdateReasonsPaginationResponse. :param items: The items of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :type: list[UpdateReason] """ self._items = items def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(DataSourceUpdateReasonsPaginationResponse, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, DataSourceUpdateReasonsPaginationResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
30.005882
304
0.612625
import pprint import re import six from logicmonitor_sdk.models.update_reason import UpdateReason class DataSourceUpdateReasonsPaginationResponse(object): swagger_types = { 'total': 'int', 'search_id': 'str', 'items': 'list[UpdateReason]' } attribute_map = { 'total': 'total', 'search_id': 'searchId', 'items': 'items' } def __init__(self, total=None, search_id=None, items=None): self._total = None self._search_id = None self._items = None self.discriminator = None if total is not None: self.total = total if search_id is not None: self.search_id = search_id if items is not None: self.items = items @property def total(self): return self._total @total.setter def total(self, total): self._total = total @property def search_id(self): return self._search_id @search_id.setter def search_id(self, search_id): self._search_id = search_id @property def items(self): return self._items @items.setter def items(self, items): self._items = items def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(DataSourceUpdateReasonsPaginationResponse, dict): for key, value in self.items(): result[key] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, DataSourceUpdateReasonsPaginationResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
f7278d910a0798fa44f63254194a56095117de1f
3,950
py
Python
superset/embedded/api.py
7vikpeculiar/superset
800ced5e257d5d83d6dbe4ced0e7318ac40d026f
[ "Apache-2.0" ]
null
null
null
superset/embedded/api.py
7vikpeculiar/superset
800ced5e257d5d83d6dbe4ced0e7318ac40d026f
[ "Apache-2.0" ]
null
null
null
superset/embedded/api.py
7vikpeculiar/superset
800ced5e257d5d83d6dbe4ced0e7318ac40d026f
[ "Apache-2.0" ]
null
null
null
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import logging from typing import Optional from flask import Response from flask_appbuilder.api import expose, protect, safe from flask_appbuilder.hooks import before_request from flask_appbuilder.models.sqla.interface import SQLAInterface from superset import is_feature_enabled from superset.constants import MODEL_API_RW_METHOD_PERMISSION_MAP, RouteMethod from superset.dashboards.schemas import EmbeddedDashboardResponseSchema from superset.embedded.dao import EmbeddedDAO from superset.embedded_dashboard.commands.exceptions import ( EmbeddedDashboardNotFoundError, ) from superset.extensions import event_logger from superset.models.embedded_dashboard import EmbeddedDashboard from superset.reports.logs.schemas import openapi_spec_methods_override from superset.views.base_api import BaseSupersetModelRestApi, statsd_metrics logger = logging.getLogger(__name__) class EmbeddedDashboardRestApi(BaseSupersetModelRestApi): datamodel = SQLAInterface(EmbeddedDashboard) @before_request def ensure_embedded_enabled(self) -> Optional[Response]: if not is_feature_enabled("EMBEDDED_SUPERSET"): return self.response_404() return None include_route_methods = RouteMethod.GET class_permission_name = "EmbeddedDashboard" method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP resource_name = "embedded_dashboard" allow_browser_login = True openapi_spec_tag = "Embedded Dashboard" openapi_spec_methods = openapi_spec_methods_override embedded_response_schema = EmbeddedDashboardResponseSchema() @expose("/<uuid>", methods=["GET"]) @protect() @safe @statsd_metrics @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get_embedded", log_to_statsd=False, ) # pylint: disable=arguments-differ, arguments-renamed) def get(self, uuid: str) -> Response: """Response Returns the dashboard's embedded configuration --- get: description: >- Returns the dashboard's embedded configuration parameters: - in: path schema: type: string name: uuid description: The embedded configuration uuid responses: 200: description: Result contains the embedded dashboard configuration content: application/json: schema: type: object properties: result: $ref: '#/components/schemas/EmbeddedDashboardResponseSchema' 401: $ref: '#/components/responses/404' 500: $ref: '#/components/responses/500' """ try: embedded = EmbeddedDAO.find_by_id(uuid) if not embedded: raise EmbeddedDashboardNotFoundError() result = self.embedded_response_schema.dump(embedded) return self.response(200, result=result) except EmbeddedDashboardNotFoundError: return self.response_404()
37.264151
87
0.704051
import logging from typing import Optional from flask import Response from flask_appbuilder.api import expose, protect, safe from flask_appbuilder.hooks import before_request from flask_appbuilder.models.sqla.interface import SQLAInterface from superset import is_feature_enabled from superset.constants import MODEL_API_RW_METHOD_PERMISSION_MAP, RouteMethod from superset.dashboards.schemas import EmbeddedDashboardResponseSchema from superset.embedded.dao import EmbeddedDAO from superset.embedded_dashboard.commands.exceptions import ( EmbeddedDashboardNotFoundError, ) from superset.extensions import event_logger from superset.models.embedded_dashboard import EmbeddedDashboard from superset.reports.logs.schemas import openapi_spec_methods_override from superset.views.base_api import BaseSupersetModelRestApi, statsd_metrics logger = logging.getLogger(__name__) class EmbeddedDashboardRestApi(BaseSupersetModelRestApi): datamodel = SQLAInterface(EmbeddedDashboard) @before_request def ensure_embedded_enabled(self) -> Optional[Response]: if not is_feature_enabled("EMBEDDED_SUPERSET"): return self.response_404() return None include_route_methods = RouteMethod.GET class_permission_name = "EmbeddedDashboard" method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP resource_name = "embedded_dashboard" allow_browser_login = True openapi_spec_tag = "Embedded Dashboard" openapi_spec_methods = openapi_spec_methods_override embedded_response_schema = EmbeddedDashboardResponseSchema() @expose("/<uuid>", methods=["GET"]) @protect() @safe @statsd_metrics @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get_embedded", log_to_statsd=False, ) def get(self, uuid: str) -> Response: try: embedded = EmbeddedDAO.find_by_id(uuid) if not embedded: raise EmbeddedDashboardNotFoundError() result = self.embedded_response_schema.dump(embedded) return self.response(200, result=result) except EmbeddedDashboardNotFoundError: return self.response_404()
true
true
f7278e0192857e4135b5b9ed6748496b57e99211
1,132
py
Python
udemy/01_walkthrough/practice_1.py
inderpal2406/python
7bd7d03a6b3cd09ff16a4447ff495a2393a87a33
[ "MIT" ]
null
null
null
udemy/01_walkthrough/practice_1.py
inderpal2406/python
7bd7d03a6b3cd09ff16a4447ff495a2393a87a33
[ "MIT" ]
null
null
null
udemy/01_walkthrough/practice_1.py
inderpal2406/python
7bd7d03a6b3cd09ff16a4447ff495a2393a87a33
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # This script will accept user input as a string. # Then display this string in left, right, center of a line in title format. string=input("Enter the string: ") # read input string string=string.title() # convert string to title format ''' # in windows cmd, mode command tells us width of a line as 122, need to check similar command in linux # in linux terminal, 'tput cols' and 'tput rows' commands lets us know the no of columns and rows in terminal, respectively # its 142 cols in linux terminal print(f"{string.ljust(142)}") # display to left print(f"{string.center(142)}") # display at center print(f"{string.rjust(142)}") # display to right ''' # this script may not display output properly if run on linux/windows terminal on other system. # So, to overcome this, we'll use os module import os width=os.get_terminal_size().columns print(f"{string.ljust(width)}") print(f"{string.center(width)}") print(f"{string.rjust(width)}") # or instead of converting the string to title format separately, # print(f"{string.ljust(width).title()}") # we can apply title operation befor ljust operation
37.733333
123
0.736749
string=input("Enter the string: ") string=string.title() import os width=os.get_terminal_size().columns print(f"{string.ljust(width)}") print(f"{string.center(width)}") print(f"{string.rjust(width)}") # or instead of converting the string to title format separately, # print(f"{string.ljust(width).title()}") # we can apply title operation befor ljust operation
true
true
f7278f1e85d824afdd21dc3d53f33b966aca7692
5,600
py
Python
copulas/multivariate/base.py
DAI-Lab/Copulas
d634437aeac02f46615398463038455260b3de25
[ "MIT" ]
71
2018-06-20T12:07:34.000Z
2020-01-03T21:43:01.000Z
copulas/multivariate/base.py
DAI-Lab/Copulas
d634437aeac02f46615398463038455260b3de25
[ "MIT" ]
75
2018-06-20T09:46:07.000Z
2019-12-23T15:04:19.000Z
copulas/multivariate/base.py
DAI-Lab/Copulas
d634437aeac02f46615398463038455260b3de25
[ "MIT" ]
25
2018-06-24T18:01:11.000Z
2020-01-02T14:30:09.000Z
"""Base Multivariate class.""" import pickle import numpy as np from copulas import NotFittedError, get_instance, validate_random_state class Multivariate(object): """Abstract class for a multi-variate copula object.""" fitted = False def __init__(self, random_state=None): self.random_state = validate_random_state(random_state) def fit(self, X): """Fit the model to table with values from multiple random variables. Arguments: X (pandas.DataFrame): Values of the random variables. """ raise NotImplementedError def probability_density(self, X): """Compute the probability density for each point in X. Arguments: X (pandas.DataFrame): Values for which the probability density will be computed. Returns: numpy.ndarray: Probability density values for points in X. Raises: NotFittedError: if the model is not fitted. """ raise NotImplementedError def log_probability_density(self, X): """Compute the log of the probability density for each point in X. Arguments: X (pandas.DataFrame): Values for which the log probability density will be computed. Returns: numpy.ndarray: Log probability density values for points in X. Raises: NotFittedError: if the model is not fitted. """ return np.log(self.probability_density(X)) def pdf(self, X): """Compute the probability density for each point in X. Arguments: X (pandas.DataFrame): Values for which the probability density will be computed. Returns: numpy.ndarray: Probability density values for points in X. Raises: NotFittedError: if the model is not fitted. """ return self.probability_density(X) def cumulative_distribution(self, X): """Compute the cumulative distribution value for each point in X. Arguments: X (pandas.DataFrame): Values for which the cumulative distribution will be computed. Returns: numpy.ndarray: Cumulative distribution values for points in X. Raises: NotFittedError: if the model is not fitted. """ raise NotImplementedError def cdf(self, X): """Compute the cumulative distribution value for each point in X. Arguments: X (pandas.DataFrame): Values for which the cumulative distribution will be computed. Returns: numpy.ndarray: Cumulative distribution values for points in X. Raises: NotFittedError: if the model is not fitted. """ return self.cumulative_distribution(X) def set_random_state(self, random_state): """Set the random state. Args: random_state (int, np.random.RandomState, or None): Seed or RandomState for the random generator. """ self.random_state = validate_random_state(random_state) def sample(self, num_rows=1): """Sample values from this model. Argument: num_rows (int): Number of rows to sample. Returns: numpy.ndarray: Array of shape (n_samples, *) with values randomly sampled from this model distribution. Raises: NotFittedError: if the model is not fitted. """ raise NotImplementedError def to_dict(self): """Return a `dict` with the parameters to replicate this object. Returns: dict: Parameters of this distribution. """ raise NotImplementedError @classmethod def from_dict(cls, params): """Create a new instance from a parameters dictionary. Args: params (dict): Parameters of the distribution, in the same format as the one returned by the ``to_dict`` method. Returns: Multivariate: Instance of the distribution defined on the parameters. """ multivariate_class = get_instance(params['type']) return multivariate_class.from_dict(params) @classmethod def load(cls, path): """Load a Multivariate instance from a pickle file. Args: path (str): Path to the pickle file where the distribution has been serialized. Returns: Multivariate: Loaded instance. """ with open(path, 'rb') as pickle_file: return pickle.load(pickle_file) def save(self, path): """Serialize this multivariate instance using pickle. Args: path (str): Path to where this distribution will be serialized. """ with open(path, 'wb') as pickle_file: pickle.dump(self, pickle_file) def check_fit(self): """Check whether this model has already been fit to a random variable. Raise a ``NotFittedError`` if it has not. Raises: NotFittedError: if the model is not fitted. """ if not self.fitted: raise NotFittedError('This model is not fitted.')
28
83
0.574821
import pickle import numpy as np from copulas import NotFittedError, get_instance, validate_random_state class Multivariate(object): fitted = False def __init__(self, random_state=None): self.random_state = validate_random_state(random_state) def fit(self, X): raise NotImplementedError def probability_density(self, X): raise NotImplementedError def log_probability_density(self, X): return np.log(self.probability_density(X)) def pdf(self, X): return self.probability_density(X) def cumulative_distribution(self, X): raise NotImplementedError def cdf(self, X): return self.cumulative_distribution(X) def set_random_state(self, random_state): self.random_state = validate_random_state(random_state) def sample(self, num_rows=1): raise NotImplementedError def to_dict(self): raise NotImplementedError @classmethod def from_dict(cls, params): multivariate_class = get_instance(params['type']) return multivariate_class.from_dict(params) @classmethod def load(cls, path): with open(path, 'rb') as pickle_file: return pickle.load(pickle_file) def save(self, path): with open(path, 'wb') as pickle_file: pickle.dump(self, pickle_file) def check_fit(self): if not self.fitted: raise NotFittedError('This model is not fitted.')
true
true
f7278fb2e4cecf1623625e589a46c10c6f0fc89f
2,209
py
Python
lowder/__init__.py
jabernardo/lowder
d7ddc7d2217ba4ab3f2a4f00314b600af9cf0e70
[ "MIT" ]
1
2020-03-02T05:02:33.000Z
2020-03-02T05:02:33.000Z
lowder/__init__.py
jabernardo/lowder
d7ddc7d2217ba4ab3f2a4f00314b600af9cf0e70
[ "MIT" ]
null
null
null
lowder/__init__.py
jabernardo/lowder
d7ddc7d2217ba4ab3f2a4f00314b600af9cf0e70
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import time import threading LOADERS = { 'default': { 'interval': 0.1, 'frames': ('/', '-', '|', '\\', '-') }, 'dots': { 'interval': 0.2, 'frames': ('⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏') }, 'dots-bar': { 'interval': 0.2, 'frames': ('. ', ' . ', ' . ',' . ', ' .', ' . ', ' . ', ' . ') }, 'bar': { 'interval': 0.2, 'frames': ('- ', ' = ', ' - ',' = ', ' -', ' = ', ' - ', ' = ') }, 'arrow': { 'interval': 0.2, 'frames': ('> ', ' > ', ' > ',' > ', ' >', ' < ', ' < ', ' < ') } } class Lowder: __run = True __loader_screen = LOADERS['default'] __result = None __loading_message = "" def __init__(self): super().__init__() def stop(self, message = None): self.__run = False cols = len(self.__loading_message) if not message is None: print(f"\x1b[${cols}D\x1b[K{message}") else: print(f"\x1b[${cols}D\x1b[K", end="\r") def __loader(self, message): while self.__run: for char in self.__loader_screen['frames']: cols = len(message) self.__loading_message = f"\x1b[${cols}D\x1b[K{char} {message}" if self.__run: print(self.__loading_message, end="\r") time.sleep(self.__loader_screen['interval']) def __call(self, callback): self.__result = callback() def start(self, message, callback, loader = LOADERS['default']): self.__loader_screen = loader self.__run = True y = threading.Thread(target=self.__call, args=(callback,)) y.start() x = threading.Thread(target=self.__loader, args=(message,)) x.start() x.join() y.join() return self.__result
28.320513
79
0.383884
import time import threading LOADERS = { 'default': { 'interval': 0.1, 'frames': ('/', '-', '|', '\\', '-') }, 'dots': { 'interval': 0.2, 'frames': ('⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏') }, 'dots-bar': { 'interval': 0.2, 'frames': ('. ', ' . ', ' . ',' . ', ' .', ' . ', ' . ', ' . ') }, 'bar': { 'interval': 0.2, 'frames': ('- ', ' = ', ' - ',' = ', ' -', ' = ', ' - ', ' = ') }, 'arrow': { 'interval': 0.2, 'frames': ('> ', ' > ', ' > ',' > ', ' >', ' < ', ' < ', ' < ') } } class Lowder: __run = True __loader_screen = LOADERS['default'] __result = None __loading_message = "" def __init__(self): super().__init__() def stop(self, message = None): self.__run = False cols = len(self.__loading_message) if not message is None: print(f"\x1b[${cols}D\x1b[K{message}") else: print(f"\x1b[${cols}D\x1b[K", end="\r") def __loader(self, message): while self.__run: for char in self.__loader_screen['frames']: cols = len(message) self.__loading_message = f"\x1b[${cols}D\x1b[K{char} {message}" if self.__run: print(self.__loading_message, end="\r") time.sleep(self.__loader_screen['interval']) def __call(self, callback): self.__result = callback() def start(self, message, callback, loader = LOADERS['default']): self.__loader_screen = loader self.__run = True y = threading.Thread(target=self.__call, args=(callback,)) y.start() x = threading.Thread(target=self.__loader, args=(message,)) x.start() x.join() y.join() return self.__result
true
true
f72790e1400c04034e99a0a996957a5a2bd3bdfa
14,106
py
Python
giung2/modeling/backbone/resnet.py
cs-giung/giung2
c8560fd1b56f20eb1f3cf57202975d8325b591f5
[ "MIT" ]
4
2021-10-18T05:15:59.000Z
2022-03-09T04:29:05.000Z
giung2/modeling/backbone/resnet.py
cs-giung/giung2
c8560fd1b56f20eb1f3cf57202975d8325b591f5
[ "MIT" ]
null
null
null
giung2/modeling/backbone/resnet.py
cs-giung/giung2
c8560fd1b56f20eb1f3cf57202975d8325b591f5
[ "MIT" ]
3
2022-01-12T11:47:51.000Z
2022-03-18T06:28:22.000Z
import torch import torch.nn as nn from typing import Dict, List from functools import partial from fvcore.common.config import CfgNode from giung2.layers import * __all__ = [ "build_resnet_backbone", ] class IdentityShortcut(nn.Module): def __init__( self, in_planes: int, planes: int, stride: int, expansion: int, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(IdentityShortcut, self).__init__() self.identity = MaxPool2d(kernel_size=1, stride=stride) self.pad_size = expansion * planes - in_planes def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.identity(x) out = nn.functional.pad(out, (0, 0, 0, 0, 0, self.pad_size), mode="constant", value=0) return out class ProjectionShortcut(nn.Module): def __init__( self, in_planes: int, planes: int, stride: int, expansion: int, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(ProjectionShortcut, self).__init__() self.conv = conv(in_channels=in_planes, out_channels=expansion*planes, kernel_size=1, stride=stride, padding=0, **kwargs) self.norm = norm(num_features=expansion*planes) def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.norm(self.conv(x, **kwargs), **kwargs) return out class FirstBlock(nn.Module): def __init__( self, in_planes: int, planes: int, conv: nn.Module, conv_ksp: List[int], norm: nn.Module, relu: nn.Module, pool: nn.Module, pool_ksp: List[int], **kwargs ) -> None: super(FirstBlock, self).__init__() self.conv1 = conv(in_channels=in_planes, out_channels=planes, kernel_size=conv_ksp[0], stride=conv_ksp[1], padding=conv_ksp[2], **kwargs) self.norm1 = norm(num_features=planes) self.relu1 = relu() self.pool1 = pool(kernel_size=pool_ksp[0], stride=pool_ksp[1], padding=pool_ksp[2]) def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.pool1(self.relu1(self.norm1(self.conv1(x, **kwargs), **kwargs), **kwargs), **kwargs) return out class BasicBlock(nn.Module): expansion = 1 def __init__( self, in_planes: int, planes: int, stride: int, shortcut: nn.Module, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(BasicBlock,self).__init__() self.conv1 = conv(in_channels=in_planes, out_channels=planes, kernel_size=3, stride=stride, padding=1, **kwargs) self.norm1 = norm(num_features=planes) self.relu1 = relu() self.conv2 = conv(in_channels=planes, out_channels=self.expansion*planes, kernel_size=3, stride=1, padding=1, **kwargs) self.norm2 = norm(num_features=self.expansion*planes) self.relu2 = relu() if stride != 1 or in_planes != self.expansion * planes: self.shortcut = shortcut( in_planes, planes, stride, self.expansion, conv, norm, **kwargs ) else: self.shortcut = Identity() def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.relu1(self.norm1(self.conv1(x, **kwargs), **kwargs), **kwargs) out = self.relu2(self.norm2(self.conv2(out, **kwargs), **kwargs) + self.shortcut(x, **kwargs), **kwargs) return out class Bottleneck(nn.Module): expansion = 4 def __init__( self, in_planes: int, planes: int, stride: int, shortcut: nn.Module, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(Bottleneck,self).__init__() self.conv1 = conv(in_channels=in_planes, out_channels=planes, kernel_size=1, stride=1, padding=0, **kwargs) self.norm1 = norm(num_features=planes) self.relu1 = relu() self.conv2 = conv(in_channels=planes, out_channels=planes, kernel_size=3, stride=stride, padding=1, **kwargs) self.norm2 = norm(num_features=planes) self.relu2 = relu() self.conv3 = conv(in_channels=planes, out_channels=self.expansion*planes, kernel_size=1, stride=1, padding=0, **kwargs) self.norm3 = norm(num_features=self.expansion*planes) self.relu3 = relu() if stride != 1 or in_planes != self.expansion * planes: self.shortcut = shortcut( in_planes, planes, stride, self.expansion, conv, norm, **kwargs ) else: self.shortcut = Identity() def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.relu1(self.norm1(self.conv1(x, **kwargs), **kwargs), **kwargs) out = self.relu2(self.norm2(self.conv2(out, **kwargs), **kwargs), **kwargs) out = self.relu3(self.norm3(self.conv3(out, **kwargs), **kwargs) + self.shortcut(x, **kwargs), **kwargs) return out class ResNet(nn.Module): def __init__( self, channels: int, in_planes: int, first_block: nn.Module, block: nn.Module, shortcut: nn.Module, num_blocks: List[int], widen_factor: int, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(ResNet, self).__init__() self.channels = channels self.in_planes = in_planes self._in_planes = in_planes self.first_block = first_block self.block = block self.shortcut = shortcut self.num_blocks = num_blocks self.widen_factor = widen_factor self.conv = conv self.norm = norm self.relu = relu _layers = [self.first_block(in_planes=self.channels, planes=self.in_planes, **kwargs)] _layers += self._make_layer( self.in_planes * self.widen_factor, self.num_blocks[0], stride=1, **kwargs ) for idx, num_block in enumerate(self.num_blocks[1:], start=1): _layers += self._make_layer( self.in_planes * (2 ** idx) * self.widen_factor, num_block, stride=2, **kwargs ) self.layers = nn.Sequential(*_layers) def _make_layer(self, planes: int, num_block: int, stride: int, **kwargs) -> List[nn.Module]: strides = [stride] + [1] * (num_block - 1) _layers = [] for stride in strides: _layers.append(self.block(self._in_planes, planes, stride, self.shortcut, self.conv, self.norm, self.relu, **kwargs)) self._in_planes = planes * self.block.expansion return _layers def forward(self, x: torch.Tensor, **kwargs) -> Dict[str, torch.Tensor]: outputs = dict() # intermediate feature maps for layer_idx, layer in enumerate(self.layers): x = layer(x, **kwargs) outputs[f"layer{layer_idx}"] = x # final feature vector x = nn.functional.adaptive_avg_pool2d(x, (1, 1)) x = x.view(x.size(0), -1) outputs["features"] = x return outputs def build_resnet_backbone(cfg: CfgNode) -> nn.Module: # Conv2d layers may be replaced by its variations _conv_layers = cfg.MODEL.BACKBONE.RESNET.CONV_LAYERS kwargs = { "bias": cfg.MODEL.BACKBONE.RESNET.CONV_LAYERS_BIAS, "same_padding": cfg.MODEL.BACKBONE.RESNET.CONV_LAYERS_SAME_PADDING, } if _conv_layers == "Conv2d": conv_layers = Conv2d elif _conv_layers == "Conv2d_Bezier": conv_layers = Conv2d_Bezier elif _conv_layers in ["Conv2d_BatchEnsemble", "Conv2d_BatchEnsembleV2",]: if cfg.MODEL.BATCH_ENSEMBLE.ENABLED is False: raise AssertionError( f"Set MODEL.BATCH_ENSEMBLE.ENABLED=True to use {_conv_layers}" ) if _conv_layers == "Conv2d_BatchEnsemble": conv_layers = Conv2d_BatchEnsemble if _conv_layers == "Conv2d_BatchEnsembleV2": conv_layers = Conv2d_BatchEnsembleV2 kwargs.update({ "ensemble_size": cfg.MODEL.BATCH_ENSEMBLE.ENSEMBLE_SIZE, "use_ensemble_bias": cfg.MODEL.BATCH_ENSEMBLE.USE_ENSEMBLE_BIAS, "alpha_initializer": { "initializer": cfg.MODEL.BATCH_ENSEMBLE.ALPHA_INITIALIZER.NAME, "init_values": cfg.MODEL.BATCH_ENSEMBLE.ALPHA_INITIALIZER.VALUES, }, "gamma_initializer": { "initializer": cfg.MODEL.BATCH_ENSEMBLE.GAMMA_INITIALIZER.NAME, "init_values": cfg.MODEL.BATCH_ENSEMBLE.GAMMA_INITIALIZER.VALUES, }, }) elif _conv_layers == "Conv2d_Dropout": if cfg.MODEL.DROPOUT.ENABLED is False: raise AssertionError( f"Set MODEL.DROPOUT.ENABLED=True to use {_conv_layers}" ) conv_layers = Conv2d_Dropout kwargs.update({ "drop_p": cfg.MODEL.DROPOUT.DROP_PROBABILITY, }) elif _conv_layers == "Conv2d_SpatialDropout": if cfg.MODEL.SPATIAL_DROPOUT.ENABLED is False: raise AssertionError( f"Set MODEL.SPATIAL_DROPOUT.ENABLED=True to use {_conv_layers}" ) conv_layers = Conv2d_SpatialDropout kwargs.update({ "drop_p": cfg.MODEL.SPATIAL_DROPOUT.DROP_PROBABILITY, }) elif _conv_layers == "Conv2d_DropBlock": if cfg.MODEL.DROP_BLOCK.ENABLED is False: raise AssertionError( f"Set MODEL.DROP_BLOCK.ENABLED=True to use {_conv_layers}" ) conv_layers = Conv2d_DropBlock kwargs.update({ "drop_p": cfg.MODEL.DROP_BLOCK.DROP_PROBABILITY, "block_size": cfg.MODEL.DROP_BLOCK.BLOCK_SIZE, "use_shared_masks": cfg.MODEL.DROP_BLOCK.USE_SHARED_MASKS, }) else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.CONV_LAYERS: {_conv_layers}" ) # BatchNorm2d layers may be replaced by its variations _norm_layers = cfg.MODEL.BACKBONE.RESNET.NORM_LAYERS if _norm_layers == "NONE": norm_layers = Identity elif _norm_layers == "BatchNorm2d": norm_layers = BatchNorm2d elif _norm_layers == "GroupNorm2d": norm_layers = partial(GroupNorm2d, num_groups=cfg.MODEL.BACKBONE.RESNET.IN_PLANES // 2) elif _norm_layers == "FilterResponseNorm2d": norm_layers = FilterResponseNorm2d elif _norm_layers == "FilterResponseNorm2d_Bezier": norm_layers = FilterResponseNorm2d_Bezier else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.NORM_LAYERS: {_norm_layers}" ) # ReLU layers may be replaced by its variations _activations = cfg.MODEL.BACKBONE.RESNET.ACTIVATIONS if _activations == "NONE": activations = Identity elif _activations == "ReLU": activations = ReLU elif _activations == "SiLU": activations = SiLU else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.ACTIVATIONS: {_activations}" ) # specify the first block first_block = partial( FirstBlock, conv = conv_layers, conv_ksp = cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.CONV_KSP, norm = norm_layers if cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.USE_NORM_LAYER else Identity, relu = activations if cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.USE_ACTIVATION else Identity, pool = MaxPool2d if cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.USE_POOL_LAYER else Identity, pool_ksp = cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.POOL_KSP, ) # specify block _block = cfg.MODEL.BACKBONE.RESNET.BLOCK if _block == "BasicBlock": block = BasicBlock elif _block == "Bottleneck": block = Bottleneck else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.BLOCK: {_block}" ) # specify shortcut _shortcut = cfg.MODEL.BACKBONE.RESNET.SHORTCUT if _shortcut == "IdentityShortcut": shortcut = IdentityShortcut elif _shortcut == "ProjectionShortcut": shortcut = ProjectionShortcut else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.SHORTCUT: {_shortcut}" ) # build backbone backbone = ResNet( channels = cfg.MODEL.BACKBONE.RESNET.CHANNELS, in_planes = cfg.MODEL.BACKBONE.RESNET.IN_PLANES, first_block = first_block, block = block, shortcut = shortcut, num_blocks = cfg.MODEL.BACKBONE.RESNET.NUM_BLOCKS, widen_factor = cfg.MODEL.BACKBONE.RESNET.WIDEN_FACTOR, conv = conv_layers, norm = norm_layers, relu = activations, **kwargs ) # initialize weights for m in backbone.modules(): if isinstance(m, Conv2d): if isinstance(m.weight, nn.ParameterList): for idx in range(len(m.weight)): nn.init.kaiming_normal_(m.weight[idx], mode="fan_out", nonlinearity="relu") else: nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") return backbone
36.638961
112
0.59223
import torch import torch.nn as nn from typing import Dict, List from functools import partial from fvcore.common.config import CfgNode from giung2.layers import * __all__ = [ "build_resnet_backbone", ] class IdentityShortcut(nn.Module): def __init__( self, in_planes: int, planes: int, stride: int, expansion: int, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(IdentityShortcut, self).__init__() self.identity = MaxPool2d(kernel_size=1, stride=stride) self.pad_size = expansion * planes - in_planes def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.identity(x) out = nn.functional.pad(out, (0, 0, 0, 0, 0, self.pad_size), mode="constant", value=0) return out class ProjectionShortcut(nn.Module): def __init__( self, in_planes: int, planes: int, stride: int, expansion: int, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(ProjectionShortcut, self).__init__() self.conv = conv(in_channels=in_planes, out_channels=expansion*planes, kernel_size=1, stride=stride, padding=0, **kwargs) self.norm = norm(num_features=expansion*planes) def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.norm(self.conv(x, **kwargs), **kwargs) return out class FirstBlock(nn.Module): def __init__( self, in_planes: int, planes: int, conv: nn.Module, conv_ksp: List[int], norm: nn.Module, relu: nn.Module, pool: nn.Module, pool_ksp: List[int], **kwargs ) -> None: super(FirstBlock, self).__init__() self.conv1 = conv(in_channels=in_planes, out_channels=planes, kernel_size=conv_ksp[0], stride=conv_ksp[1], padding=conv_ksp[2], **kwargs) self.norm1 = norm(num_features=planes) self.relu1 = relu() self.pool1 = pool(kernel_size=pool_ksp[0], stride=pool_ksp[1], padding=pool_ksp[2]) def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.pool1(self.relu1(self.norm1(self.conv1(x, **kwargs), **kwargs), **kwargs), **kwargs) return out class BasicBlock(nn.Module): expansion = 1 def __init__( self, in_planes: int, planes: int, stride: int, shortcut: nn.Module, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(BasicBlock,self).__init__() self.conv1 = conv(in_channels=in_planes, out_channels=planes, kernel_size=3, stride=stride, padding=1, **kwargs) self.norm1 = norm(num_features=planes) self.relu1 = relu() self.conv2 = conv(in_channels=planes, out_channels=self.expansion*planes, kernel_size=3, stride=1, padding=1, **kwargs) self.norm2 = norm(num_features=self.expansion*planes) self.relu2 = relu() if stride != 1 or in_planes != self.expansion * planes: self.shortcut = shortcut( in_planes, planes, stride, self.expansion, conv, norm, **kwargs ) else: self.shortcut = Identity() def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.relu1(self.norm1(self.conv1(x, **kwargs), **kwargs), **kwargs) out = self.relu2(self.norm2(self.conv2(out, **kwargs), **kwargs) + self.shortcut(x, **kwargs), **kwargs) return out class Bottleneck(nn.Module): expansion = 4 def __init__( self, in_planes: int, planes: int, stride: int, shortcut: nn.Module, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(Bottleneck,self).__init__() self.conv1 = conv(in_channels=in_planes, out_channels=planes, kernel_size=1, stride=1, padding=0, **kwargs) self.norm1 = norm(num_features=planes) self.relu1 = relu() self.conv2 = conv(in_channels=planes, out_channels=planes, kernel_size=3, stride=stride, padding=1, **kwargs) self.norm2 = norm(num_features=planes) self.relu2 = relu() self.conv3 = conv(in_channels=planes, out_channels=self.expansion*planes, kernel_size=1, stride=1, padding=0, **kwargs) self.norm3 = norm(num_features=self.expansion*planes) self.relu3 = relu() if stride != 1 or in_planes != self.expansion * planes: self.shortcut = shortcut( in_planes, planes, stride, self.expansion, conv, norm, **kwargs ) else: self.shortcut = Identity() def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.relu1(self.norm1(self.conv1(x, **kwargs), **kwargs), **kwargs) out = self.relu2(self.norm2(self.conv2(out, **kwargs), **kwargs), **kwargs) out = self.relu3(self.norm3(self.conv3(out, **kwargs), **kwargs) + self.shortcut(x, **kwargs), **kwargs) return out class ResNet(nn.Module): def __init__( self, channels: int, in_planes: int, first_block: nn.Module, block: nn.Module, shortcut: nn.Module, num_blocks: List[int], widen_factor: int, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(ResNet, self).__init__() self.channels = channels self.in_planes = in_planes self._in_planes = in_planes self.first_block = first_block self.block = block self.shortcut = shortcut self.num_blocks = num_blocks self.widen_factor = widen_factor self.conv = conv self.norm = norm self.relu = relu _layers = [self.first_block(in_planes=self.channels, planes=self.in_planes, **kwargs)] _layers += self._make_layer( self.in_planes * self.widen_factor, self.num_blocks[0], stride=1, **kwargs ) for idx, num_block in enumerate(self.num_blocks[1:], start=1): _layers += self._make_layer( self.in_planes * (2 ** idx) * self.widen_factor, num_block, stride=2, **kwargs ) self.layers = nn.Sequential(*_layers) def _make_layer(self, planes: int, num_block: int, stride: int, **kwargs) -> List[nn.Module]: strides = [stride] + [1] * (num_block - 1) _layers = [] for stride in strides: _layers.append(self.block(self._in_planes, planes, stride, self.shortcut, self.conv, self.norm, self.relu, **kwargs)) self._in_planes = planes * self.block.expansion return _layers def forward(self, x: torch.Tensor, **kwargs) -> Dict[str, torch.Tensor]: outputs = dict() for layer_idx, layer in enumerate(self.layers): x = layer(x, **kwargs) outputs[f"layer{layer_idx}"] = x x = nn.functional.adaptive_avg_pool2d(x, (1, 1)) x = x.view(x.size(0), -1) outputs["features"] = x return outputs def build_resnet_backbone(cfg: CfgNode) -> nn.Module: _conv_layers = cfg.MODEL.BACKBONE.RESNET.CONV_LAYERS kwargs = { "bias": cfg.MODEL.BACKBONE.RESNET.CONV_LAYERS_BIAS, "same_padding": cfg.MODEL.BACKBONE.RESNET.CONV_LAYERS_SAME_PADDING, } if _conv_layers == "Conv2d": conv_layers = Conv2d elif _conv_layers == "Conv2d_Bezier": conv_layers = Conv2d_Bezier elif _conv_layers in ["Conv2d_BatchEnsemble", "Conv2d_BatchEnsembleV2",]: if cfg.MODEL.BATCH_ENSEMBLE.ENABLED is False: raise AssertionError( f"Set MODEL.BATCH_ENSEMBLE.ENABLED=True to use {_conv_layers}" ) if _conv_layers == "Conv2d_BatchEnsemble": conv_layers = Conv2d_BatchEnsemble if _conv_layers == "Conv2d_BatchEnsembleV2": conv_layers = Conv2d_BatchEnsembleV2 kwargs.update({ "ensemble_size": cfg.MODEL.BATCH_ENSEMBLE.ENSEMBLE_SIZE, "use_ensemble_bias": cfg.MODEL.BATCH_ENSEMBLE.USE_ENSEMBLE_BIAS, "alpha_initializer": { "initializer": cfg.MODEL.BATCH_ENSEMBLE.ALPHA_INITIALIZER.NAME, "init_values": cfg.MODEL.BATCH_ENSEMBLE.ALPHA_INITIALIZER.VALUES, }, "gamma_initializer": { "initializer": cfg.MODEL.BATCH_ENSEMBLE.GAMMA_INITIALIZER.NAME, "init_values": cfg.MODEL.BATCH_ENSEMBLE.GAMMA_INITIALIZER.VALUES, }, }) elif _conv_layers == "Conv2d_Dropout": if cfg.MODEL.DROPOUT.ENABLED is False: raise AssertionError( f"Set MODEL.DROPOUT.ENABLED=True to use {_conv_layers}" ) conv_layers = Conv2d_Dropout kwargs.update({ "drop_p": cfg.MODEL.DROPOUT.DROP_PROBABILITY, }) elif _conv_layers == "Conv2d_SpatialDropout": if cfg.MODEL.SPATIAL_DROPOUT.ENABLED is False: raise AssertionError( f"Set MODEL.SPATIAL_DROPOUT.ENABLED=True to use {_conv_layers}" ) conv_layers = Conv2d_SpatialDropout kwargs.update({ "drop_p": cfg.MODEL.SPATIAL_DROPOUT.DROP_PROBABILITY, }) elif _conv_layers == "Conv2d_DropBlock": if cfg.MODEL.DROP_BLOCK.ENABLED is False: raise AssertionError( f"Set MODEL.DROP_BLOCK.ENABLED=True to use {_conv_layers}" ) conv_layers = Conv2d_DropBlock kwargs.update({ "drop_p": cfg.MODEL.DROP_BLOCK.DROP_PROBABILITY, "block_size": cfg.MODEL.DROP_BLOCK.BLOCK_SIZE, "use_shared_masks": cfg.MODEL.DROP_BLOCK.USE_SHARED_MASKS, }) else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.CONV_LAYERS: {_conv_layers}" ) _norm_layers = cfg.MODEL.BACKBONE.RESNET.NORM_LAYERS if _norm_layers == "NONE": norm_layers = Identity elif _norm_layers == "BatchNorm2d": norm_layers = BatchNorm2d elif _norm_layers == "GroupNorm2d": norm_layers = partial(GroupNorm2d, num_groups=cfg.MODEL.BACKBONE.RESNET.IN_PLANES // 2) elif _norm_layers == "FilterResponseNorm2d": norm_layers = FilterResponseNorm2d elif _norm_layers == "FilterResponseNorm2d_Bezier": norm_layers = FilterResponseNorm2d_Bezier else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.NORM_LAYERS: {_norm_layers}" ) _activations = cfg.MODEL.BACKBONE.RESNET.ACTIVATIONS if _activations == "NONE": activations = Identity elif _activations == "ReLU": activations = ReLU elif _activations == "SiLU": activations = SiLU else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.ACTIVATIONS: {_activations}" ) first_block = partial( FirstBlock, conv = conv_layers, conv_ksp = cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.CONV_KSP, norm = norm_layers if cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.USE_NORM_LAYER else Identity, relu = activations if cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.USE_ACTIVATION else Identity, pool = MaxPool2d if cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.USE_POOL_LAYER else Identity, pool_ksp = cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.POOL_KSP, ) _block = cfg.MODEL.BACKBONE.RESNET.BLOCK if _block == "BasicBlock": block = BasicBlock elif _block == "Bottleneck": block = Bottleneck else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.BLOCK: {_block}" ) _shortcut = cfg.MODEL.BACKBONE.RESNET.SHORTCUT if _shortcut == "IdentityShortcut": shortcut = IdentityShortcut elif _shortcut == "ProjectionShortcut": shortcut = ProjectionShortcut else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.SHORTCUT: {_shortcut}" ) backbone = ResNet( channels = cfg.MODEL.BACKBONE.RESNET.CHANNELS, in_planes = cfg.MODEL.BACKBONE.RESNET.IN_PLANES, first_block = first_block, block = block, shortcut = shortcut, num_blocks = cfg.MODEL.BACKBONE.RESNET.NUM_BLOCKS, widen_factor = cfg.MODEL.BACKBONE.RESNET.WIDEN_FACTOR, conv = conv_layers, norm = norm_layers, relu = activations, **kwargs ) for m in backbone.modules(): if isinstance(m, Conv2d): if isinstance(m.weight, nn.ParameterList): for idx in range(len(m.weight)): nn.init.kaiming_normal_(m.weight[idx], mode="fan_out", nonlinearity="relu") else: nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") return backbone
true
true
f727917d0f068e8d6007ff3141a9580153e749e9
4,756
py
Python
dipy/data/tests/test_fetcher.py
nasimanousheh/dipy
d737a6af80a184322e30de4760e8c205291dbed0
[ "MIT" ]
2
2018-07-25T14:04:20.000Z
2021-02-10T07:10:10.000Z
dipy/data/tests/test_fetcher.py
aarya22/dipy-reco1
9d20c911b4afe83e52ded698eff9ba0f0fafeca8
[ "MIT" ]
null
null
null
dipy/data/tests/test_fetcher.py
aarya22/dipy-reco1
9d20c911b4afe83e52ded698eff9ba0f0fafeca8
[ "MIT" ]
2
2018-07-24T21:20:54.000Z
2018-08-27T04:08:24.000Z
import tempfile import os.path as op import sys import os import numpy.testing as npt from nibabel.tmpdirs import TemporaryDirectory import dipy.data.fetcher as fetcher from dipy.data import SPHERE_FILES from threading import Thread if sys.version_info[0] < 3: from SimpleHTTPServer import SimpleHTTPRequestHandler # Python 2 from SocketServer import TCPServer as HTTPServer else: from http.server import HTTPServer, SimpleHTTPRequestHandler # Python 3 def test_check_md5(): fd, fname = tempfile.mkstemp() stored_md5 = fetcher._get_file_md5(fname) # If all is well, this shouldn't return anything: npt.assert_equal(fetcher.check_md5(fname, stored_md5), None) # If None is provided as input, it should silently not check either: npt.assert_equal(fetcher.check_md5(fname, None), None) # Otherwise, it will raise its exception class: npt.assert_raises(fetcher.FetcherError, fetcher.check_md5, fname, 'foo') def test_make_fetcher(): symmetric362 = SPHERE_FILES['symmetric362'] with TemporaryDirectory() as tmpdir: stored_md5 = fetcher._get_file_md5(symmetric362) # create local HTTP Server testfile_url = op.split(symmetric362)[0] + os.sep test_server_url = "http://127.0.0.1:8000/" print(testfile_url) print(symmetric362) current_dir = os.getcwd() # change pwd to directory containing testfile. os.chdir(testfile_url) server = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler) server_thread = Thread(target=server.serve_forever) server_thread.deamon = True server_thread.start() # test make_fetcher sphere_fetcher = fetcher._make_fetcher("sphere_fetcher", tmpdir, test_server_url, [op.split(symmetric362)[-1]], ["sphere_name"], md5_list=[stored_md5]) sphere_fetcher() assert op.isfile(op.join(tmpdir, "sphere_name")) npt.assert_equal(fetcher._get_file_md5(op.join(tmpdir, "sphere_name")), stored_md5) # stop local HTTP Server server.shutdown() # change to original working directory os.chdir(current_dir) def test_fetch_data(): symmetric362 = SPHERE_FILES['symmetric362'] with TemporaryDirectory() as tmpdir: md5 = fetcher._get_file_md5(symmetric362) bad_md5 = '8' * len(md5) newfile = op.join(tmpdir, "testfile.txt") # Test that the fetcher can get a file testfile_url = symmetric362 print(testfile_url) testfile_dir, testfile_name = op.split(testfile_url) # create local HTTP Server test_server_url = "http://127.0.0.1:8001/" + testfile_name current_dir = os.getcwd() # change pwd to directory containing testfile. os.chdir(testfile_dir + os.sep) # use different port as shutdown() takes time to release socket. server = HTTPServer(('localhost', 8001), SimpleHTTPRequestHandler) server_thread = Thread(target=server.serve_forever) server_thread.deamon = True server_thread.start() files = {"testfile.txt": (test_server_url, md5)} fetcher.fetch_data(files, tmpdir) npt.assert_(op.exists(newfile)) # Test that the file is replaced when the md5 doesn't match with open(newfile, 'a') as f: f.write("some junk") fetcher.fetch_data(files, tmpdir) npt.assert_(op.exists(newfile)) npt.assert_equal(fetcher._get_file_md5(newfile), md5) # Test that an error is raised when the md5 checksum of the download # file does not match the expected value files = {"testfile.txt": (test_server_url, bad_md5)} npt.assert_raises(fetcher.FetcherError, fetcher.fetch_data, files, tmpdir) # stop local HTTP Server server.shutdown() # change to original working directory os.chdir(current_dir) def test_dipy_home(): test_path = 'TEST_PATH' if 'DIPY_HOME' in os.environ: old_home = os.environ['DIPY_HOME'] del os.environ['DIPY_HOME'] else: old_home = None reload(fetcher) npt.assert_string_equal(fetcher.dipy_home, op.join(os.path.expanduser('~'), '.dipy')) os.environ['DIPY_HOME'] = test_path reload(fetcher) npt.assert_string_equal(fetcher.dipy_home, test_path) # return to previous state if old_home: os.environ['DIPY_HOME'] = old_home
37.448819
79
0.634567
import tempfile import os.path as op import sys import os import numpy.testing as npt from nibabel.tmpdirs import TemporaryDirectory import dipy.data.fetcher as fetcher from dipy.data import SPHERE_FILES from threading import Thread if sys.version_info[0] < 3: from SimpleHTTPServer import SimpleHTTPRequestHandler from SocketServer import TCPServer as HTTPServer else: from http.server import HTTPServer, SimpleHTTPRequestHandler def test_check_md5(): fd, fname = tempfile.mkstemp() stored_md5 = fetcher._get_file_md5(fname) npt.assert_equal(fetcher.check_md5(fname, stored_md5), None) # If None is provided as input, it should silently not check either: npt.assert_equal(fetcher.check_md5(fname, None), None) # Otherwise, it will raise its exception class: npt.assert_raises(fetcher.FetcherError, fetcher.check_md5, fname, 'foo') def test_make_fetcher(): symmetric362 = SPHERE_FILES['symmetric362'] with TemporaryDirectory() as tmpdir: stored_md5 = fetcher._get_file_md5(symmetric362) # create local HTTP Server testfile_url = op.split(symmetric362)[0] + os.sep test_server_url = "http://127.0.0.1:8000/" print(testfile_url) print(symmetric362) current_dir = os.getcwd() # change pwd to directory containing testfile. os.chdir(testfile_url) server = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler) server_thread = Thread(target=server.serve_forever) server_thread.deamon = True server_thread.start() # test make_fetcher sphere_fetcher = fetcher._make_fetcher("sphere_fetcher", tmpdir, test_server_url, [op.split(symmetric362)[-1]], ["sphere_name"], md5_list=[stored_md5]) sphere_fetcher() assert op.isfile(op.join(tmpdir, "sphere_name")) npt.assert_equal(fetcher._get_file_md5(op.join(tmpdir, "sphere_name")), stored_md5) # stop local HTTP Server server.shutdown() # change to original working directory os.chdir(current_dir) def test_fetch_data(): symmetric362 = SPHERE_FILES['symmetric362'] with TemporaryDirectory() as tmpdir: md5 = fetcher._get_file_md5(symmetric362) bad_md5 = '8' * len(md5) newfile = op.join(tmpdir, "testfile.txt") # Test that the fetcher can get a file testfile_url = symmetric362 print(testfile_url) testfile_dir, testfile_name = op.split(testfile_url) # create local HTTP Server test_server_url = "http://127.0.0.1:8001/" + testfile_name current_dir = os.getcwd() # change pwd to directory containing testfile. os.chdir(testfile_dir + os.sep) # use different port as shutdown() takes time to release socket. server = HTTPServer(('localhost', 8001), SimpleHTTPRequestHandler) server_thread = Thread(target=server.serve_forever) server_thread.deamon = True server_thread.start() files = {"testfile.txt": (test_server_url, md5)} fetcher.fetch_data(files, tmpdir) npt.assert_(op.exists(newfile)) # Test that the file is replaced when the md5 doesn't match with open(newfile, 'a') as f: f.write("some junk") fetcher.fetch_data(files, tmpdir) npt.assert_(op.exists(newfile)) npt.assert_equal(fetcher._get_file_md5(newfile), md5) files = {"testfile.txt": (test_server_url, bad_md5)} npt.assert_raises(fetcher.FetcherError, fetcher.fetch_data, files, tmpdir) server.shutdown() os.chdir(current_dir) def test_dipy_home(): test_path = 'TEST_PATH' if 'DIPY_HOME' in os.environ: old_home = os.environ['DIPY_HOME'] del os.environ['DIPY_HOME'] else: old_home = None reload(fetcher) npt.assert_string_equal(fetcher.dipy_home, op.join(os.path.expanduser('~'), '.dipy')) os.environ['DIPY_HOME'] = test_path reload(fetcher) npt.assert_string_equal(fetcher.dipy_home, test_path) if old_home: os.environ['DIPY_HOME'] = old_home
true
true
f727925dfeb5359a5f6f7116be96d12c7354d32c
4,577
py
Python
jarviscli/plugins/bmr.py
jronzo99/Jarvis
d63b51a1a7cb5bbff36e6e7dc3c63201ae1470b2
[ "MIT" ]
1
2021-05-25T11:29:25.000Z
2021-05-25T11:29:25.000Z
jarviscli/plugins/bmr.py
nikiboura/Jarvis
eb22f7c84a345e9ae5925b4b98adbc4f2e4a93f3
[ "MIT" ]
null
null
null
jarviscli/plugins/bmr.py
nikiboura/Jarvis
eb22f7c84a345e9ae5925b4b98adbc4f2e4a93f3
[ "MIT" ]
null
null
null
from colorama import Fore from plugin import plugin @plugin("bmr") def bmr(jarvis, s): """A Jarvis plugin to calculate your Basal Metabolic Rate (BMR) and your Active Metabolic Rate(AMR)""" jarvis.say("Hello there! Ready to count your BMR? \n") jarvis.say("1. Yes, let's start! \n2. Sorry," " I don't know what BMR is :( \n ") jarvis.say("Please enter your choice: ") # validate the input for choice choice = jarvis.input() while True: if choice == "1" or choice == "2": break else: jarvis.say("Sorry, invalid input was given. Try again! \n") jarvis.say("Please enter your choice: ") choice = jarvis.input() # print definition of BMR if choice == "2": jarvis.say("\nBasal Metabolic Rate (BMR)", Fore.GREEN) jarvis.say("is the number of calories your body needs" "\nto accomplish its most basic (basal)\n" "life-sustaining functions. \n") jarvis.say("Since you know now, let's calculate it! \n") # gets inputs and makes the necessary checks jarvis.say("What's your gender? (M/F)") while True: sex = jarvis.input() # ignore lower or upper letters if sex.upper() == "M" or sex.upper() == "F": break jarvis.say("Sorry, invalid input was given!" "Please try again. (M/F)") jarvis.say("What is your height (cm) ?") while True: try: height = int(jarvis.input()) if height <= 0: raise ValueError break except ValueError: print("Oops! That was no valid number. Try again...") jarvis.say("What is your weight (kg) ?") while True: try: weight = int(jarvis.input()) if weight <= 0: raise ValueError break except ValueError: print("Oops! That was no valid number. Try again...") jarvis.say("What is your age ?") while True: try: age = int(jarvis.input()) if age <= 0: raise ValueError break except ValueError: print("Oops! That was no valid number. Try again...") # formula changes based on sex if sex.upper() == 'F': bmr = (float(height) * 6.25) + (float(weight) * 9.99) - \ (float(age) * 4.92) - 116 elif sex.upper() == 'M': bmr = (float(height) * 6.25) + (float(weight) * 9.99) - \ (float(age) * 4.92) - 5 jarvis.say("BMR: " + str(bmr), Fore.GREEN) jarvis.say("\nNow that you know your BMR,\nwould you like to calculate " "your AMR too based on it?\n") # print definition of AMR jarvis.say("Active Metabolic Rate (AMR)", Fore.GREEN) jarvis.say("is the actual amount of calories you burn\n" "each day due to physical activities\n" "like going to the gym, aerobics\n") jarvis.say("Please enter your choice(Y/N): ") amr_choice = jarvis.input() # choice of calculating the amr or not while True: if amr_choice.upper() == "Y" or amr_choice.upper() == "N": break else: jarvis.say("Sorry, invalid input was given. Try again! \n") jarvis.say("Please enter your choice(Y/N): ") amr_choice = jarvis.input() if amr_choice.upper() == "N": jarvis.say("Okay, bye!", Fore.BLUE) else: jarvis.say("Please enter your exercise level: \n") jarvis.say("1.Low\n2.Average\n3.High\n4.Every Day\n5.Athletic") jarvis.say("Please enter your choice: ") # input for exercise level # based on the above choices exercise_level = jarvis.input() level_choices = ("1", "2", "3", "4", "5") while True: if exercise_level in level_choices: break else: jarvis.say("Sorry, invalid input was given. Try again! \n") jarvis.say("Please enter your choice: ") exercise_level = jarvis.input() # calculate the amr # depending on the exercise level if exercise_level == "1": amr = bmr * 1.2 if exercise_level == "2": amr = bmr * 1.375 if exercise_level == "3": amr = bmr * 1.55 if exercise_level == "4": amr = bmr * 1.725 if exercise_level == "5": amr = bmr * 1.9 jarvis.say("AMR: " + str(amr), Fore.GREEN)
35.757813
76
0.537688
from colorama import Fore from plugin import plugin @plugin("bmr") def bmr(jarvis, s): jarvis.say("Hello there! Ready to count your BMR? \n") jarvis.say("1. Yes, let's start! \n2. Sorry," " I don't know what BMR is :( \n ") jarvis.say("Please enter your choice: ") choice = jarvis.input() while True: if choice == "1" or choice == "2": break else: jarvis.say("Sorry, invalid input was given. Try again! \n") jarvis.say("Please enter your choice: ") choice = jarvis.input() if choice == "2": jarvis.say("\nBasal Metabolic Rate (BMR)", Fore.GREEN) jarvis.say("is the number of calories your body needs" "\nto accomplish its most basic (basal)\n" "life-sustaining functions. \n") jarvis.say("Since you know now, let's calculate it! \n") # gets inputs and makes the necessary checks jarvis.say("What's your gender? (M/F)") while True: sex = jarvis.input() if sex.upper() == "M" or sex.upper() == "F": break jarvis.say("Sorry, invalid input was given!" "Please try again. (M/F)") jarvis.say("What is your height (cm) ?") while True: try: height = int(jarvis.input()) if height <= 0: raise ValueError break except ValueError: print("Oops! That was no valid number. Try again...") jarvis.say("What is your weight (kg) ?") while True: try: weight = int(jarvis.input()) if weight <= 0: raise ValueError break except ValueError: print("Oops! That was no valid number. Try again...") jarvis.say("What is your age ?") while True: try: age = int(jarvis.input()) if age <= 0: raise ValueError break except ValueError: print("Oops! That was no valid number. Try again...") if sex.upper() == 'F': bmr = (float(height) * 6.25) + (float(weight) * 9.99) - \ (float(age) * 4.92) - 116 elif sex.upper() == 'M': bmr = (float(height) * 6.25) + (float(weight) * 9.99) - \ (float(age) * 4.92) - 5 jarvis.say("BMR: " + str(bmr), Fore.GREEN) jarvis.say("\nNow that you know your BMR,\nwould you like to calculate " "your AMR too based on it?\n") jarvis.say("Active Metabolic Rate (AMR)", Fore.GREEN) jarvis.say("is the actual amount of calories you burn\n" "each day due to physical activities\n" "like going to the gym, aerobics\n") jarvis.say("Please enter your choice(Y/N): ") amr_choice = jarvis.input() while True: if amr_choice.upper() == "Y" or amr_choice.upper() == "N": break else: jarvis.say("Sorry, invalid input was given. Try again! \n") jarvis.say("Please enter your choice(Y/N): ") amr_choice = jarvis.input() if amr_choice.upper() == "N": jarvis.say("Okay, bye!", Fore.BLUE) else: jarvis.say("Please enter your exercise level: \n") jarvis.say("1.Low\n2.Average\n3.High\n4.Every Day\n5.Athletic") jarvis.say("Please enter your choice: ") exercise_level = jarvis.input() level_choices = ("1", "2", "3", "4", "5") while True: if exercise_level in level_choices: break else: jarvis.say("Sorry, invalid input was given. Try again! \n") jarvis.say("Please enter your choice: ") exercise_level = jarvis.input() if exercise_level == "1": amr = bmr * 1.2 if exercise_level == "2": amr = bmr * 1.375 if exercise_level == "3": amr = bmr * 1.55 if exercise_level == "4": amr = bmr * 1.725 if exercise_level == "5": amr = bmr * 1.9 jarvis.say("AMR: " + str(amr), Fore.GREEN)
true
true
f7279315c269b9d8ccac798e0d91c3ab9cba61d7
3,834
py
Python
Project/_visualize.py
BendeguzToth/NeuralLanguageModel
f4bb60375019acd57c7396768d62ad0f3166391c
[ "MIT" ]
1
2021-05-18T04:04:31.000Z
2021-05-18T04:04:31.000Z
Project/_visualize.py
BendeguzToth/NeuralLanguageModel
f4bb60375019acd57c7396768d62ad0f3166391c
[ "MIT" ]
null
null
null
Project/_visualize.py
BendeguzToth/NeuralLanguageModel
f4bb60375019acd57c7396768d62ad0f3166391c
[ "MIT" ]
null
null
null
""" In this file we visualize the activations of particular neurons, at different positions of a provided sample text. """ # Standard libraries import json import tkinter as tk # Third-party libraries import numpy as np # Project files from layers import LSTM # SETUP MODEL = "saves/ShakespeareNet.json" LOOKUP_FILE = "saves/ShakespeareLookup.json" TEXT_FILE = "saves/sample.txt" def main(): with open(LOOKUP_FILE, 'r') as file: chars = json.load(file) # Here we make dictionaries that can be used to convert # between characters, integer id-s of characters, and one-hot # vectors that will be used to represent the characters. char_to_int = dict() int_to_char = dict() char_to_vec = dict() for i in range(len(chars)): char_to_int[chars[i]] = i int_to_char[i] = chars[i] vec = np.zeros((len(chars), 1)) vec[i] = 1. char_to_vec[chars[i]] = vec # The length of the vector that represents a character # is equivalent to the number of different characters # in the text. EMBEDDING_LENGTH = len(chars) # Create the LSTM layers only. We don't use the Network class, # since we are only interested in the activations of the recurrent # layers. first_layer = LSTM(size=512, input_size=EMBEDDING_LENGTH, batch_size=1, backprop_depth=1, stateful=True) second_layer = LSTM(size=512, input_size=512, batch_size=1, backprop_depth=1, stateful=True) # Load the weights. with open(MODEL, 'r') as file: weights = json.load(file) first_layer.loadParams(weights[0]) second_layer.loadParams(weights[1]) # Loading in the file. with open(TEXT_FILE, 'r', encoding='utf8') as file: text = file.read() source = list(text) for i in range(len(source)): source[i] = char_to_vec[source[i]] # Feed the text to the network. # Here we look at the activation of the neurons of the # hidden state at the 2nd LSTM layer. # We take the first element of the output as there is only one # batch. out = second_layer.forward(first_layer.forward(np.array([source])))[0] # ###############---TKINTER---############################################# class Wrap: NEURON_INDEX = 0 def showNeuron(): for j in range(out.shape[0]): # We will leave the background of the newline characters white, # regardless of its activation. The reason for that is that the color # would fill the entire remainder of the line, which is very disturbing to look at. intensity = 255 if text[j] == '\n' else 255 - int((out[j, Wrap.NEURON_INDEX, 0] + 1) * 127.5) text_box.tag_config(str(j), background="#%02x%02x%02x" % ( 255, intensity, intensity)) def inputFromEntry(evt): Wrap.NEURON_INDEX = int(entry.get()) entry.delete(0, "end") showNeuron() def nextButtonClicked(): Wrap.NEURON_INDEX += 1 entry.delete(0, "end") entry.insert(tk.INSERT, str(Wrap.NEURON_INDEX)) showNeuron() # Making the tkinter window. root = tk.Tk() text_box = tk.Text(root, height=35) text_box.insert(tk.INSERT, text) text_box.pack() current_line = 1 current_char = 0 for i in range(out.shape[0]): text_box.tag_add(str(i), f"{current_line}.{current_char}") current_char += 1 if text[i] == '\n': current_line += 1 current_char = 0 # Making the entry box. entry = tk.Entry(root, width=5) entry.pack() entry.bind("<Return>", inputFromEntry) # Buttons up = tk.Button(text="Next", command=nextButtonClicked) up.pack() # Show the first neuron by default. showNeuron() root.mainloop() if __name__ == '__main__': main()
30.188976
108
0.628326
import json import tkinter as tk import numpy as np from layers import LSTM MODEL = "saves/ShakespeareNet.json" LOOKUP_FILE = "saves/ShakespeareLookup.json" TEXT_FILE = "saves/sample.txt" def main(): with open(LOOKUP_FILE, 'r') as file: chars = json.load(file) char_to_int = dict() int_to_char = dict() char_to_vec = dict() for i in range(len(chars)): char_to_int[chars[i]] = i int_to_char[i] = chars[i] vec = np.zeros((len(chars), 1)) vec[i] = 1. char_to_vec[chars[i]] = vec EMBEDDING_LENGTH = len(chars) # since we are only interested in the activations of the recurrent # layers. first_layer = LSTM(size=512, input_size=EMBEDDING_LENGTH, batch_size=1, backprop_depth=1, stateful=True) second_layer = LSTM(size=512, input_size=512, batch_size=1, backprop_depth=1, stateful=True) # Load the weights. with open(MODEL, 'r') as file: weights = json.load(file) first_layer.loadParams(weights[0]) second_layer.loadParams(weights[1]) # Loading in the file. with open(TEXT_FILE, 'r', encoding='utf8') as file: text = file.read() source = list(text) for i in range(len(source)): source[i] = char_to_vec[source[i]] # Feed the text to the network. # Here we look at the activation of the neurons of the # hidden state at the 2nd LSTM layer. # We take the first element of the output as there is only one # batch. out = second_layer.forward(first_layer.forward(np.array([source])))[0] # ###############---TKINTER---############################################# class Wrap: NEURON_INDEX = 0 def showNeuron(): for j in range(out.shape[0]): # We will leave the background of the newline characters white, # regardless of its activation. The reason for that is that the color # would fill the entire remainder of the line, which is very disturbing to look at. intensity = 255 if text[j] == '\n' else 255 - int((out[j, Wrap.NEURON_INDEX, 0] + 1) * 127.5) text_box.tag_config(str(j), background="#%02x%02x%02x" % ( 255, intensity, intensity)) def inputFromEntry(evt): Wrap.NEURON_INDEX = int(entry.get()) entry.delete(0, "end") showNeuron() def nextButtonClicked(): Wrap.NEURON_INDEX += 1 entry.delete(0, "end") entry.insert(tk.INSERT, str(Wrap.NEURON_INDEX)) showNeuron() # Making the tkinter window. root = tk.Tk() text_box = tk.Text(root, height=35) text_box.insert(tk.INSERT, text) text_box.pack() current_line = 1 current_char = 0 for i in range(out.shape[0]): text_box.tag_add(str(i), f"{current_line}.{current_char}") current_char += 1 if text[i] == '\n': current_line += 1 current_char = 0 # Making the entry box. entry = tk.Entry(root, width=5) entry.pack() entry.bind("<Return>", inputFromEntry) # Buttons up = tk.Button(text="Next", command=nextButtonClicked) up.pack() # Show the first neuron by default. showNeuron() root.mainloop() if __name__ == '__main__': main()
true
true
f72793d54ac528bc12e6cc394f04adc65956cb34
21,296
py
Python
gen_data_fin.py
vjaguilera/BERT4Rec
8c460676af224c90c9cc89f1ba837b38f04e4210
[ "Apache-2.0" ]
null
null
null
gen_data_fin.py
vjaguilera/BERT4Rec
8c460676af224c90c9cc89f1ba837b38f04e4210
[ "Apache-2.0" ]
null
null
null
gen_data_fin.py
vjaguilera/BERT4Rec
8c460676af224c90c9cc89f1ba837b38f04e4210
[ "Apache-2.0" ]
null
null
null
# -*- coding: UTF-8 -*- import os import codecs import collections import random import sys import tensorflow as tf import six from util import * from vocab import * import pickle import multiprocessing import time random_seed = 12345 short_seq_prob = 0 # Probability of creating sequences which are shorter than the maximum length。 flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_string("signature", 'default', "signature_name") flags.DEFINE_integer( "pool_size", 10, "multiprocesses pool size.") flags.DEFINE_integer( "max_seq_length", 200, "max sequence length.") flags.DEFINE_integer( "max_predictions_per_seq", 20, "max_predictions_per_seq.") flags.DEFINE_float( "masked_lm_prob", 0.15, "Masked LM probability.") flags.DEFINE_float( "mask_prob", 1.0, "mask probabaility") flags.DEFINE_integer( "dupe_factor", 10, "Number of times to duplicate the input data (with different masks).") flags.DEFINE_float("prop_sliding_window", 0.1, "sliding window step size.") flags.DEFINE_string( "data_dir", './data/', "data dir.") flags.DEFINE_string( "dataset_name", 'ml-1m', "dataset name.") def printable_text(text): """Returns text encoded in a way suitable for print or `tf.logging`.""" # These functions want `str` for both Python2 and Python3, but in one case # it's a Unicode string and in the other it's a byte string. if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text))) elif six.PY2: if isinstance(text, str): return text elif isinstance(text, unicode): return text.encode("utf-8") else: raise ValueError("Unsupported string type: %s" % (type(text))) else: raise ValueError("Not running on Python2 or Python 3?") def convert_to_unicode(text): """Converts `text` to Unicode (if it's not already), assuming utf-8 input.""" if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text))) elif six.PY2: if isinstance(text, str): return text.decode("utf-8", "ignore") elif isinstance(text, unicode): return text else: raise ValueError("Unsupported string type: %s" % (type(text))) else: raise ValueError("Not running on Python2 or Python 3?") class TrainingInstance(object): """A single training instance (sentence pair).""" def __init__(self, info, tokens, masked_lm_positions, masked_lm_labels): self.info = info # info = [user] self.tokens = tokens self.masked_lm_positions = masked_lm_positions self.masked_lm_labels = masked_lm_labels def __str__(self): s = "" s += "info: %s\n" % (" ".join([printable_text(x) for x in self.info])) s += "tokens: %s\n" % ( " ".join([printable_text(x) for x in self.tokens])) s += "masked_lm_positions: %s\n" % ( " ".join([str(x) for x in self.masked_lm_positions])) s += "masked_lm_labels: %s\n" % ( " ".join([printable_text(x) for x in self.masked_lm_labels])) s += "\n" return s def __repr__(self): return self.__str__() def write_instance_to_example_files(instances, max_seq_length, max_predictions_per_seq, vocab, output_files): """Create TF example files from `TrainingInstance`s.""" writers = [] for output_file in output_files: writers.append(tf.python_io.TFRecordWriter(output_file)) writer_index = 0 total_written = 0 for (inst_index, instance) in enumerate(instances): try: input_ids = vocab.convert_tokens_to_ids(instance.tokens) except: print(instance) input_mask = [1] * len(input_ids) assert len(input_ids) <= max_seq_length input_ids += [0] * (max_seq_length - len(input_ids)) input_mask += [0] * (max_seq_length - len(input_mask)) assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length masked_lm_positions = list(instance.masked_lm_positions) masked_lm_ids = vocab.convert_tokens_to_ids(instance.masked_lm_labels) masked_lm_weights = [1.0] * len(masked_lm_ids) masked_lm_positions += [0] * (max_predictions_per_seq - len(masked_lm_positions)) masked_lm_ids += [0] * (max_predictions_per_seq - len(masked_lm_ids)) masked_lm_weights += [0.0] * (max_predictions_per_seq - len(masked_lm_weights)) features = collections.OrderedDict() features["info"] = create_int_feature(instance.info) features["input_ids"] = create_int_feature(input_ids) features["input_mask"] = create_int_feature(input_mask) features["masked_lm_positions"] = create_int_feature( masked_lm_positions) features["masked_lm_ids"] = create_int_feature(masked_lm_ids) features["masked_lm_weights"] = create_float_feature(masked_lm_weights) tf_example = tf.train.Example( features=tf.train.Features(feature=features)) writers[writer_index].write(tf_example.SerializeToString()) writer_index = (writer_index + 1) % len(writers) total_written += 1 if inst_index < 20: tf.logging.info("*** Example ***") tf.logging.info("tokens: %s" % " ".join( [printable_text(x) for x in instance.tokens])) for feature_name in features.keys(): feature = features[feature_name] values = [] if feature.int64_list.value: values = feature.int64_list.value elif feature.float_list.value: values = feature.float_list.value tf.logging.info("%s: %s" % (feature_name, " ".join([str(x) for x in values]))) for writer in writers: writer.close() tf.logging.info("Wrote %d total instances", total_written) def create_int_feature(values): feature = tf.train.Feature( int64_list=tf.train.Int64List(value=list(values))) return feature def create_float_feature(values): feature = tf.train.Feature( float_list=tf.train.FloatList(value=list(values))) return feature def create_training_instances(all_documents_raw, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng, vocab, mask_prob, prop_sliding_window, pool_size, force_last=False): """Create `TrainingInstance`s from raw text. PARAMS: - all_documents_raw (dict): Dict containing users as keys and item-list as value """ all_documents = {} # TEST if force_last: max_num_tokens = max_seq_length for user, item_seq in all_documents_raw.items(): if len(item_seq) == 0: print("got empty seq:" + user) continue all_documents[user] = [item_seq[-max_num_tokens:]] # Assign list of list from the last to the max_num_tokens # TRAIN else: max_num_tokens = max_seq_length # we need two sentence sliding_step = (int)( prop_sliding_window * max_num_tokens) if prop_sliding_window != -1.0 else max_num_tokens for user, item_seq in all_documents_raw.items(): if len(item_seq) == 0: print("got empty seq:" + user) continue #todo: add slide if len(item_seq) <= max_num_tokens: # All to token all_documents[user] = [item_seq] else: beg_idx = list(range(len(item_seq)-max_num_tokens, 0, -sliding_step)) beg_idx.append(0) # Reverse ordered list with 0 appended all_documents[user] = [item_seq[i:i + max_num_tokens] for i in beg_idx[::-1]] instances = [] # TEST if force_last: for user in all_documents: instances.extend( create_instances_from_document_test( all_documents, user, max_seq_length)) print("num of instance:{}".format(len(instances))) # TRAIN else: start_time = time.clock() pool = multiprocessing.Pool(processes=pool_size) instances = [] print("Document quantity: {}".format(len(all_documents))) def log_result(result): print("callback function result type: {}, size: {} ".format(type(result), len(result))) # RESULT CAN BE error_callback or the result of create_instances_threading instances.extend(result) # Add Training Instances to instances list if result is correct for step in range(dupe_factor): # Run a process async as a thread pool.apply_async( create_instances_threading, args=( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, random.Random(random.randint(1,10000)), mask_prob, step, dupe_factor), callback=log_result) pool.close() pool.join() # Always masking the last item for user in all_documents: instances.extend( mask_last( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng)) print("num of instance:{}; time:{}".format(len(instances), time.clock() - start_time)) rng.shuffle(instances) return instances def create_instances_threading(all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng, mask_prob, step, dupe_factor): cnt = 0 start_time = time.clock() instances = [] for user in all_documents: cnt += 1 if cnt % 1000 == 0: print("step: {}/{}, name: {}, user: {}, time: {}".format(step, dupe_factor, multiprocessing.current_process().name, cnt, time.clock()-start_time)) start_time = time.clock() instances.extend(create_instances_from_document_train( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng, mask_prob)) return instances def mask_last( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng): """Creates `TrainingInstance`s for a single document.""" document = all_documents[user] max_num_tokens = max_seq_length instances = [] info = [int(user.split("_")[1])] vocab_items = vocab.get_items() for tokens in document: assert len(tokens) >= 1 and len(tokens) <= max_num_tokens (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions_force_last(tokens) instance = TrainingInstance( info=info, tokens=tokens, masked_lm_positions=masked_lm_positions, masked_lm_labels=masked_lm_labels) instances.append(instance) return instances def create_instances_from_document_test(all_documents, user, max_seq_length): """Creates `TrainingInstance`s for a single document.""" document = all_documents[user] max_num_tokens = max_seq_length assert len(document) == 1 and len(document[0]) <= max_num_tokens tokens = document[0] assert len(tokens) >= 1 (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions_force_last(tokens) info = [int(user.split("_")[1])] instance = TrainingInstance( info=info, tokens=tokens, masked_lm_positions=masked_lm_positions, masked_lm_labels=masked_lm_labels) return [instance] def create_instances_from_document_train( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng, mask_prob): """Creates `TrainingInstance`s for a single document.""" document = all_documents[user] max_num_tokens = max_seq_length instances = [] info = [int(user.split("_")[1])] vocab_items = vocab.get_items() for tokens in document: assert len(tokens) >= 1 and len(tokens) <= max_num_tokens # Return the tokens, the masked positions and the masked labels (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions( tokens, masked_lm_prob, max_predictions_per_seq, vocab_items, rng, mask_prob) # Instantiate a TrainingInstance instance = TrainingInstance( info=info, tokens=tokens, masked_lm_positions=masked_lm_positions, masked_lm_labels=masked_lm_labels) instances.append(instance) return instances MaskedLmInstance = collections.namedtuple("MaskedLmInstance", ["index", "label"]) def create_masked_lm_predictions_force_last(tokens): """Creates the predictions for the masked LM objective, BUT JUST MASKING THE LAST ITEM""" last_index = -1 for (i, token) in enumerate(tokens): if token == "[CLS]" or token == "[PAD]" or token == '[NO_USE]': continue last_index = i assert last_index > 0 output_tokens = list(tokens) output_tokens[last_index] = "[MASK]" masked_lm_positions = [last_index] masked_lm_labels = [tokens[last_index]] return (output_tokens, masked_lm_positions, masked_lm_labels) def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng, mask_prob): """Creates the predictions for the masked LM objective.""" cand_indexes = [] for (i, token) in enumerate(tokens): if token not in vocab_words: continue cand_indexes.append(i) rng.shuffle(cand_indexes) output_tokens = list(tokens) num_to_predict = min(max_predictions_per_seq, max(1, int(round(len(tokens) * masked_lm_prob)))) masked_lms = [] covered_indexes = set() for index in cand_indexes: if len(masked_lms) >= num_to_predict: break if index in covered_indexes: continue covered_indexes.add(index) masked_token = None # 80% of the time, replace with [MASK] if rng.random() < mask_prob: masked_token = "[MASK]" else: # 10% of the time, keep original if rng.random() < 0.5: masked_token = tokens[index] # 10% of the time, replace with random word else: # masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)] masked_token = rng.choice(vocab_words) output_tokens[index] = masked_token masked_lms.append(MaskedLmInstance(index=index, label=tokens[index])) masked_lms = sorted(masked_lms, key=lambda x: x.index) masked_lm_positions = [] masked_lm_labels = [] for p in masked_lms: masked_lm_positions.append(p.index) masked_lm_labels.append(p.label) return (output_tokens, masked_lm_positions, masked_lm_labels) def gen_samples(data, output_filename, rng, vocab, max_seq_length, dupe_factor, short_seq_prob, mask_prob, masked_lm_prob, max_predictions_per_seq, prop_sliding_window, pool_size, force_last=False): # create train instances instances = create_training_instances( data, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng, vocab, mask_prob, prop_sliding_window, pool_size, force_last) tf.logging.info("*** Writing to output files ***") tf.logging.info(" %s", output_filename) # Write training instances write_instance_to_example_files(instances, max_seq_length, max_predictions_per_seq, vocab, [output_filename]) def main(): tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.DEBUG) max_seq_length = FLAGS.max_seq_length max_predictions_per_seq = FLAGS.max_predictions_per_seq masked_lm_prob = FLAGS.masked_lm_prob mask_prob = FLAGS.mask_prob dupe_factor = FLAGS.dupe_factor prop_sliding_window = FLAGS.prop_sliding_window pool_size = FLAGS.pool_size output_dir = FLAGS.data_dir dataset_name = FLAGS.dataset_name version_id = FLAGS.signature print(version_id) print(output_dir) print(dataset_name) if not os.path.isdir(output_dir): print(output_dir + ' is not exist') print(os.getcwd()) exit(1) dataset = data_partition(output_dir+dataset_name+'.txt') [user_train, user_valid, user_test, usernum, itemnum] = dataset cc = 0.0 max_len = 0 min_len = 100000 for u in user_train: cc += len(user_train[u]) max_len = max(len(user_train[u]), max_len) min_len = min(len(user_train[u]), min_len) print('average sequence length: %.2f' % (cc / len(user_train))) print('max:{}, min:{}'.format(max_len, min_len)) print('len_train:{}, len_valid:{}, len_test:{}, usernum:{}, itemnum:{}'. format( len(user_train), len(user_valid), len(user_test), usernum, itemnum)) for idx, u in enumerate(user_train): if idx < 10: print(user_train[u]) print(user_valid[u]) print(user_test[u]) # put validate into train for u in user_train: if u in user_valid: user_train[u].extend(user_valid[u]) # get the max index of the data user_train_data = { 'user_' + str(k): ['item_' + str(item) for item in v] for k, v in user_train.items() if len(v) > 0 } user_test_data = { 'user_' + str(u): ['item_' + str(item) for item in (user_train[u] + user_test[u])] for u in user_train if len(user_train[u]) > 0 and len(user_test[u]) > 0 } rng = random.Random(random_seed) vocab = FreqVocab(user_test_data) user_test_data_output = { k: [vocab.convert_tokens_to_ids(v)] for k, v in user_test_data.items() } print('begin to generate train') output_filename = output_dir + dataset_name + version_id + '.train.tfrecord' ## Generating training masked samples gen_samples( user_train_data, output_filename, rng, vocab, max_seq_length, dupe_factor, short_seq_prob, mask_prob, masked_lm_prob, max_predictions_per_seq, prop_sliding_window, pool_size, force_last=False) print('train:{}'.format(output_filename)) print('begin to generate test') output_filename = output_dir + dataset_name + version_id + '.test.tfrecord' ## Generating test masked samples ## force_last is True gen_samples( user_test_data, output_filename, rng, vocab, max_seq_length, dupe_factor, short_seq_prob, mask_prob, masked_lm_prob, max_predictions_per_seq, -1.0, pool_size, force_last=True) print('test:{}'.format(output_filename)) print('vocab_size:{}, user_size:{}, item_size:{}, item_with_other_size:{}'. format(vocab.get_vocab_size(), vocab.get_user_count(), vocab.get_item_count(), vocab.get_item_count() + vocab.get_special_token_count())) vocab_file_name = output_dir + dataset_name + version_id + '.vocab' print('vocab pickle file: ' + vocab_file_name) with open(vocab_file_name, 'wb') as output_file: pickle.dump(vocab, output_file, protocol=2) his_file_name = output_dir + dataset_name + version_id + '.his' print('test data pickle file: ' + his_file_name) with open(his_file_name, 'wb') as output_file: pickle.dump(user_test_data_output, output_file, protocol=2) print('done.') if __name__ == "__main__": main()
32.864198
158
0.609739
import os import codecs import collections import random import sys import tensorflow as tf import six from util import * from vocab import * import pickle import multiprocessing import time random_seed = 12345 short_seq_prob = 0 flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_string("signature", 'default', "signature_name") flags.DEFINE_integer( "pool_size", 10, "multiprocesses pool size.") flags.DEFINE_integer( "max_seq_length", 200, "max sequence length.") flags.DEFINE_integer( "max_predictions_per_seq", 20, "max_predictions_per_seq.") flags.DEFINE_float( "masked_lm_prob", 0.15, "Masked LM probability.") flags.DEFINE_float( "mask_prob", 1.0, "mask probabaility") flags.DEFINE_integer( "dupe_factor", 10, "Number of times to duplicate the input data (with different masks).") flags.DEFINE_float("prop_sliding_window", 0.1, "sliding window step size.") flags.DEFINE_string( "data_dir", './data/', "data dir.") flags.DEFINE_string( "dataset_name", 'ml-1m', "dataset name.") def printable_text(text): if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text))) elif six.PY2: if isinstance(text, str): return text elif isinstance(text, unicode): return text.encode("utf-8") else: raise ValueError("Unsupported string type: %s" % (type(text))) else: raise ValueError("Not running on Python2 or Python 3?") def convert_to_unicode(text): if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text))) elif six.PY2: if isinstance(text, str): return text.decode("utf-8", "ignore") elif isinstance(text, unicode): return text else: raise ValueError("Unsupported string type: %s" % (type(text))) else: raise ValueError("Not running on Python2 or Python 3?") class TrainingInstance(object): def __init__(self, info, tokens, masked_lm_positions, masked_lm_labels): self.info = info self.tokens = tokens self.masked_lm_positions = masked_lm_positions self.masked_lm_labels = masked_lm_labels def __str__(self): s = "" s += "info: %s\n" % (" ".join([printable_text(x) for x in self.info])) s += "tokens: %s\n" % ( " ".join([printable_text(x) for x in self.tokens])) s += "masked_lm_positions: %s\n" % ( " ".join([str(x) for x in self.masked_lm_positions])) s += "masked_lm_labels: %s\n" % ( " ".join([printable_text(x) for x in self.masked_lm_labels])) s += "\n" return s def __repr__(self): return self.__str__() def write_instance_to_example_files(instances, max_seq_length, max_predictions_per_seq, vocab, output_files): writers = [] for output_file in output_files: writers.append(tf.python_io.TFRecordWriter(output_file)) writer_index = 0 total_written = 0 for (inst_index, instance) in enumerate(instances): try: input_ids = vocab.convert_tokens_to_ids(instance.tokens) except: print(instance) input_mask = [1] * len(input_ids) assert len(input_ids) <= max_seq_length input_ids += [0] * (max_seq_length - len(input_ids)) input_mask += [0] * (max_seq_length - len(input_mask)) assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length masked_lm_positions = list(instance.masked_lm_positions) masked_lm_ids = vocab.convert_tokens_to_ids(instance.masked_lm_labels) masked_lm_weights = [1.0] * len(masked_lm_ids) masked_lm_positions += [0] * (max_predictions_per_seq - len(masked_lm_positions)) masked_lm_ids += [0] * (max_predictions_per_seq - len(masked_lm_ids)) masked_lm_weights += [0.0] * (max_predictions_per_seq - len(masked_lm_weights)) features = collections.OrderedDict() features["info"] = create_int_feature(instance.info) features["input_ids"] = create_int_feature(input_ids) features["input_mask"] = create_int_feature(input_mask) features["masked_lm_positions"] = create_int_feature( masked_lm_positions) features["masked_lm_ids"] = create_int_feature(masked_lm_ids) features["masked_lm_weights"] = create_float_feature(masked_lm_weights) tf_example = tf.train.Example( features=tf.train.Features(feature=features)) writers[writer_index].write(tf_example.SerializeToString()) writer_index = (writer_index + 1) % len(writers) total_written += 1 if inst_index < 20: tf.logging.info("*** Example ***") tf.logging.info("tokens: %s" % " ".join( [printable_text(x) for x in instance.tokens])) for feature_name in features.keys(): feature = features[feature_name] values = [] if feature.int64_list.value: values = feature.int64_list.value elif feature.float_list.value: values = feature.float_list.value tf.logging.info("%s: %s" % (feature_name, " ".join([str(x) for x in values]))) for writer in writers: writer.close() tf.logging.info("Wrote %d total instances", total_written) def create_int_feature(values): feature = tf.train.Feature( int64_list=tf.train.Int64List(value=list(values))) return feature def create_float_feature(values): feature = tf.train.Feature( float_list=tf.train.FloatList(value=list(values))) return feature def create_training_instances(all_documents_raw, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng, vocab, mask_prob, prop_sliding_window, pool_size, force_last=False): all_documents = {} if force_last: max_num_tokens = max_seq_length for user, item_seq in all_documents_raw.items(): if len(item_seq) == 0: print("got empty seq:" + user) continue all_documents[user] = [item_seq[-max_num_tokens:]] else: max_num_tokens = max_seq_length sliding_step = (int)( prop_sliding_window * max_num_tokens) if prop_sliding_window != -1.0 else max_num_tokens for user, item_seq in all_documents_raw.items(): if len(item_seq) == 0: print("got empty seq:" + user) continue if len(item_seq) <= max_num_tokens: all_documents[user] = [item_seq] else: beg_idx = list(range(len(item_seq)-max_num_tokens, 0, -sliding_step)) beg_idx.append(0) all_documents[user] = [item_seq[i:i + max_num_tokens] for i in beg_idx[::-1]] instances = [] if force_last: for user in all_documents: instances.extend( create_instances_from_document_test( all_documents, user, max_seq_length)) print("num of instance:{}".format(len(instances))) else: start_time = time.clock() pool = multiprocessing.Pool(processes=pool_size) instances = [] print("Document quantity: {}".format(len(all_documents))) def log_result(result): print("callback function result type: {}, size: {} ".format(type(result), len(result))) instances.extend(result) for step in range(dupe_factor): pool.apply_async( create_instances_threading, args=( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, random.Random(random.randint(1,10000)), mask_prob, step, dupe_factor), callback=log_result) pool.close() pool.join() for user in all_documents: instances.extend( mask_last( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng)) print("num of instance:{}; time:{}".format(len(instances), time.clock() - start_time)) rng.shuffle(instances) return instances def create_instances_threading(all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng, mask_prob, step, dupe_factor): cnt = 0 start_time = time.clock() instances = [] for user in all_documents: cnt += 1 if cnt % 1000 == 0: print("step: {}/{}, name: {}, user: {}, time: {}".format(step, dupe_factor, multiprocessing.current_process().name, cnt, time.clock()-start_time)) start_time = time.clock() instances.extend(create_instances_from_document_train( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng, mask_prob)) return instances def mask_last( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng): document = all_documents[user] max_num_tokens = max_seq_length instances = [] info = [int(user.split("_")[1])] vocab_items = vocab.get_items() for tokens in document: assert len(tokens) >= 1 and len(tokens) <= max_num_tokens (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions_force_last(tokens) instance = TrainingInstance( info=info, tokens=tokens, masked_lm_positions=masked_lm_positions, masked_lm_labels=masked_lm_labels) instances.append(instance) return instances def create_instances_from_document_test(all_documents, user, max_seq_length): document = all_documents[user] max_num_tokens = max_seq_length assert len(document) == 1 and len(document[0]) <= max_num_tokens tokens = document[0] assert len(tokens) >= 1 (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions_force_last(tokens) info = [int(user.split("_")[1])] instance = TrainingInstance( info=info, tokens=tokens, masked_lm_positions=masked_lm_positions, masked_lm_labels=masked_lm_labels) return [instance] def create_instances_from_document_train( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng, mask_prob): document = all_documents[user] max_num_tokens = max_seq_length instances = [] info = [int(user.split("_")[1])] vocab_items = vocab.get_items() for tokens in document: assert len(tokens) >= 1 and len(tokens) <= max_num_tokens (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions( tokens, masked_lm_prob, max_predictions_per_seq, vocab_items, rng, mask_prob) instance = TrainingInstance( info=info, tokens=tokens, masked_lm_positions=masked_lm_positions, masked_lm_labels=masked_lm_labels) instances.append(instance) return instances MaskedLmInstance = collections.namedtuple("MaskedLmInstance", ["index", "label"]) def create_masked_lm_predictions_force_last(tokens): last_index = -1 for (i, token) in enumerate(tokens): if token == "[CLS]" or token == "[PAD]" or token == '[NO_USE]': continue last_index = i assert last_index > 0 output_tokens = list(tokens) output_tokens[last_index] = "[MASK]" masked_lm_positions = [last_index] masked_lm_labels = [tokens[last_index]] return (output_tokens, masked_lm_positions, masked_lm_labels) def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng, mask_prob): cand_indexes = [] for (i, token) in enumerate(tokens): if token not in vocab_words: continue cand_indexes.append(i) rng.shuffle(cand_indexes) output_tokens = list(tokens) num_to_predict = min(max_predictions_per_seq, max(1, int(round(len(tokens) * masked_lm_prob)))) masked_lms = [] covered_indexes = set() for index in cand_indexes: if len(masked_lms) >= num_to_predict: break if index in covered_indexes: continue covered_indexes.add(index) masked_token = None if rng.random() < mask_prob: masked_token = "[MASK]" else: if rng.random() < 0.5: masked_token = tokens[index] else: masked_token = rng.choice(vocab_words) output_tokens[index] = masked_token masked_lms.append(MaskedLmInstance(index=index, label=tokens[index])) masked_lms = sorted(masked_lms, key=lambda x: x.index) masked_lm_positions = [] masked_lm_labels = [] for p in masked_lms: masked_lm_positions.append(p.index) masked_lm_labels.append(p.label) return (output_tokens, masked_lm_positions, masked_lm_labels) def gen_samples(data, output_filename, rng, vocab, max_seq_length, dupe_factor, short_seq_prob, mask_prob, masked_lm_prob, max_predictions_per_seq, prop_sliding_window, pool_size, force_last=False): instances = create_training_instances( data, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng, vocab, mask_prob, prop_sliding_window, pool_size, force_last) tf.logging.info("*** Writing to output files ***") tf.logging.info(" %s", output_filename) write_instance_to_example_files(instances, max_seq_length, max_predictions_per_seq, vocab, [output_filename]) def main(): tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.DEBUG) max_seq_length = FLAGS.max_seq_length max_predictions_per_seq = FLAGS.max_predictions_per_seq masked_lm_prob = FLAGS.masked_lm_prob mask_prob = FLAGS.mask_prob dupe_factor = FLAGS.dupe_factor prop_sliding_window = FLAGS.prop_sliding_window pool_size = FLAGS.pool_size output_dir = FLAGS.data_dir dataset_name = FLAGS.dataset_name version_id = FLAGS.signature print(version_id) print(output_dir) print(dataset_name) if not os.path.isdir(output_dir): print(output_dir + ' is not exist') print(os.getcwd()) exit(1) dataset = data_partition(output_dir+dataset_name+'.txt') [user_train, user_valid, user_test, usernum, itemnum] = dataset cc = 0.0 max_len = 0 min_len = 100000 for u in user_train: cc += len(user_train[u]) max_len = max(len(user_train[u]), max_len) min_len = min(len(user_train[u]), min_len) print('average sequence length: %.2f' % (cc / len(user_train))) print('max:{}, min:{}'.format(max_len, min_len)) print('len_train:{}, len_valid:{}, len_test:{}, usernum:{}, itemnum:{}'. format( len(user_train), len(user_valid), len(user_test), usernum, itemnum)) for idx, u in enumerate(user_train): if idx < 10: print(user_train[u]) print(user_valid[u]) print(user_test[u]) for u in user_train: if u in user_valid: user_train[u].extend(user_valid[u]) user_train_data = { 'user_' + str(k): ['item_' + str(item) for item in v] for k, v in user_train.items() if len(v) > 0 } user_test_data = { 'user_' + str(u): ['item_' + str(item) for item in (user_train[u] + user_test[u])] for u in user_train if len(user_train[u]) > 0 and len(user_test[u]) > 0 } rng = random.Random(random_seed) vocab = FreqVocab(user_test_data) user_test_data_output = { k: [vocab.convert_tokens_to_ids(v)] for k, v in user_test_data.items() } print('begin to generate train') output_filename = output_dir + dataset_name + version_id + '.train.tfrecord' _data, output_filename, rng, vocab, max_seq_length, dupe_factor, short_seq_prob, mask_prob, masked_lm_prob, max_predictions_per_seq, prop_sliding_window, pool_size, force_last=False) print('train:{}'.format(output_filename)) print('begin to generate test') output_filename = output_dir + dataset_name + version_id + '.test.tfrecord' output_filename, rng, vocab, max_seq_length, dupe_factor, short_seq_prob, mask_prob, masked_lm_prob, max_predictions_per_seq, -1.0, pool_size, force_last=True) print('test:{}'.format(output_filename)) print('vocab_size:{}, user_size:{}, item_size:{}, item_with_other_size:{}'. format(vocab.get_vocab_size(), vocab.get_user_count(), vocab.get_item_count(), vocab.get_item_count() + vocab.get_special_token_count())) vocab_file_name = output_dir + dataset_name + version_id + '.vocab' print('vocab pickle file: ' + vocab_file_name) with open(vocab_file_name, 'wb') as output_file: pickle.dump(vocab, output_file, protocol=2) his_file_name = output_dir + dataset_name + version_id + '.his' print('test data pickle file: ' + his_file_name) with open(his_file_name, 'wb') as output_file: pickle.dump(user_test_data_output, output_file, protocol=2) print('done.') if __name__ == "__main__": main()
true
true
f727954b000151483380835b1aa72d1c1ac5eccb
2,275
py
Python
src/scheduler/migrations/0004_scheduledemailaction.py
japesone/ontask_b
17af441f9893c521d2e14011e7790ba4077e3318
[ "MIT" ]
3
2018-08-24T10:48:40.000Z
2020-05-29T06:33:23.000Z
src/scheduler/migrations/0004_scheduledemailaction.py
japesone/ontask_b
17af441f9893c521d2e14011e7790ba4077e3318
[ "MIT" ]
null
null
null
src/scheduler/migrations/0004_scheduledemailaction.py
japesone/ontask_b
17af441f9893c521d2e14011e7790ba4077e3318
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-12-16 08:54 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('workflow', '0013_auto_20171209_0809'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('action', '0008_auto_20171209_1808'), ('scheduler', '0003_auto_20171216_1944'), ] operations = [ migrations.CreateModel( name='ScheduledEmailAction', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('type', models.CharField(max_length=256)), ('created', models.DateTimeField(auto_now_add=True)), ('execute', models.DateTimeField(null=True)), ('status', models.IntegerField(choices=[(0, 'pending'), (1, 'running'), (2, 'done')], verbose_name='Execution Status')), ('subject', models.CharField(blank=True, default='', max_length=2048, verbose_name='Email subject')), ('send_confirmation', models.BooleanField(default=False, verbose_name='Send you a confirmation email')), ('track_read', models.BooleanField(default=False, verbose_name='Track if emails are read?')), ('add_column', models.BooleanField(default=False, verbose_name='Add a column with the number of email reads tracked')), ('action', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='scheduled_actions', to='action.Action')), ('email_column', models.ForeignKey(db_index=False, on_delete=django.db.models.deletion.CASCADE, to='workflow.Column', verbose_name='Column containing the email address')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ('workflow', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='scheduled_actions', to='workflow.Workflow')), ], options={ 'abstract': False, }, ), ]
51.704545
187
0.648352
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('workflow', '0013_auto_20171209_0809'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('action', '0008_auto_20171209_1808'), ('scheduler', '0003_auto_20171216_1944'), ] operations = [ migrations.CreateModel( name='ScheduledEmailAction', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('type', models.CharField(max_length=256)), ('created', models.DateTimeField(auto_now_add=True)), ('execute', models.DateTimeField(null=True)), ('status', models.IntegerField(choices=[(0, 'pending'), (1, 'running'), (2, 'done')], verbose_name='Execution Status')), ('subject', models.CharField(blank=True, default='', max_length=2048, verbose_name='Email subject')), ('send_confirmation', models.BooleanField(default=False, verbose_name='Send you a confirmation email')), ('track_read', models.BooleanField(default=False, verbose_name='Track if emails are read?')), ('add_column', models.BooleanField(default=False, verbose_name='Add a column with the number of email reads tracked')), ('action', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='scheduled_actions', to='action.Action')), ('email_column', models.ForeignKey(db_index=False, on_delete=django.db.models.deletion.CASCADE, to='workflow.Column', verbose_name='Column containing the email address')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ('workflow', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='scheduled_actions', to='workflow.Workflow')), ], options={ 'abstract': False, }, ), ]
true
true
f72795aa0c613268a934fa6fe9d3601b7683d86e
20,230
py
Python
sdk/core/azure-core/azure/core/polling/base_polling.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
8
2021-01-13T23:44:08.000Z
2021-03-17T10:13:36.000Z
sdk/core/azure-core/azure/core/polling/base_polling.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
null
null
null
sdk/core/azure-core/azure/core/polling/base_polling.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
1
2020-10-11T06:05:00.000Z
2020-10-11T06:05:00.000Z
# -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. # # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the ""Software""), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # # -------------------------------------------------------------------------- import abc import base64 import json from typing import TYPE_CHECKING, Optional, Any, Union from ..exceptions import HttpResponseError, DecodeError from . import PollingMethod from ..pipeline.policies._utils import get_retry_after if TYPE_CHECKING: from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import ( HttpResponse, AsyncHttpResponse, HttpRequest, ) ResponseType = Union[HttpResponse, AsyncHttpResponse] PipelineResponseType = PipelineResponse[HttpRequest, ResponseType] try: ABC = abc.ABC except AttributeError: # Python 2.7, abc exists, but not ABC ABC = abc.ABCMeta("ABC", (object,), {"__slots__": ()}) # type: ignore _FINISHED = frozenset(["succeeded", "canceled", "failed"]) _FAILED = frozenset(["canceled", "failed"]) _SUCCEEDED = frozenset(["succeeded"]) def _finished(status): if hasattr(status, "value"): status = status.value return str(status).lower() in _FINISHED def _failed(status): if hasattr(status, "value"): status = status.value return str(status).lower() in _FAILED def _succeeded(status): if hasattr(status, "value"): status = status.value return str(status).lower() in _SUCCEEDED class BadStatus(Exception): pass class BadResponse(Exception): pass class OperationFailed(Exception): pass def _as_json(response): # type: (ResponseType) -> dict """Assuming this is not empty, return the content as JSON. Result/exceptions is not determined if you call this method without testing _is_empty. :raises: DecodeError if response body contains invalid json data. """ try: return json.loads(response.text()) except ValueError: raise DecodeError("Error occurred in deserializing the response body.") def _raise_if_bad_http_status_and_method(response): # type: (ResponseType) -> None """Check response status code is valid. Must be 200, 201, 202, or 204. :raises: BadStatus if invalid status. """ code = response.status_code if code in {200, 201, 202, 204}: return raise BadStatus( "Invalid return status {!r} for {!r} operation".format( code, response.request.method ) ) def _is_empty(response): # type: (ResponseType) -> bool """Check if response body contains meaningful content. :rtype: bool """ return not bool(response.body()) class LongRunningOperation(ABC): """LongRunningOperation Provides default logic for interpreting operation responses and status updates. :param azure.core.pipeline.PipelineResponse response: The initial pipeline response. :param callable deserialization_callback: The deserialization callaback. :param dict lro_options: LRO options. :param kwargs: Unused for now """ @abc.abstractmethod def can_poll(self, pipeline_response): # type: (PipelineResponseType) -> bool """Answer if this polling method could be used. """ raise NotImplementedError() @abc.abstractmethod def get_polling_url(self): # type: () -> str """Return the polling URL. """ raise NotImplementedError() @abc.abstractmethod def set_initial_status(self, pipeline_response): # type: (PipelineResponseType) -> str """Process first response after initiating long running operation. :param azure.core.pipeline.PipelineResponse response: initial REST call response. """ raise NotImplementedError() @abc.abstractmethod def get_status(self, pipeline_response): # type: (PipelineResponseType) -> str """Return the status string extracted from this response.""" raise NotImplementedError() @abc.abstractmethod def get_final_get_url(self, pipeline_response): # type: (PipelineResponseType) -> Optional[str] """If a final GET is needed, returns the URL. :rtype: str """ raise NotImplementedError() class OperationResourcePolling(LongRunningOperation): """Implements a operation resource polling, typically from Operation-Location. :param str operation_location_header: Name of the header to return operation format (default 'operation-location') """ def __init__(self, operation_location_header="operation-location"): self._operation_location_header = operation_location_header # Store the initial URLs self._async_url = None self._location_url = None self._request = None def can_poll(self, pipeline_response): """Answer if this polling method could be used. """ response = pipeline_response.http_response return self._operation_location_header in response.headers def get_polling_url(self): # type: () -> str """Return the polling URL. """ return self._async_url def get_final_get_url(self, pipeline_response): # type: (PipelineResponseType) -> Optional[str] """If a final GET is needed, returns the URL. :rtype: str """ response = pipeline_response.http_response if not _is_empty(response): body = _as_json(response) # https://github.com/microsoft/api-guidelines/blob/vNext/Guidelines.md#target-resource-location resource_location = body.get("resourceLocation") if resource_location: return resource_location if self._request.method in {"PUT", "PATCH"}: return self._request.url if self._request.method == "POST" and self._location_url: return self._location_url return None def set_initial_status(self, pipeline_response): # type: (PipelineResponseType) -> str """Process first response after initiating long running operation. :param azure.core.pipeline.PipelineResponse response: initial REST call response. """ self._request = pipeline_response.http_response.request response = pipeline_response.http_response self._set_async_url_if_present(response) if response.status_code in {200, 201, 202, 204} and self._async_url: return "InProgress" raise OperationFailed("Operation failed or canceled") def _set_async_url_if_present(self, response): # type: (ResponseType) -> None self._async_url = response.headers[self._operation_location_header] location_url = response.headers.get("location") if location_url: self._location_url = location_url def get_status(self, pipeline_response): # type: (PipelineResponseType) -> str """Process the latest status update retrieved from an "Operation-Location" header. :param azure.core.pipeline.PipelineResponse response: The response to extract the status. :raises: BadResponse if response has no body, or body does not contain status. """ response = pipeline_response.http_response if _is_empty(response): raise BadResponse( "The response from long running operation does not contain a body." ) body = _as_json(response) status = body.get("status") if not status: raise BadResponse("No status found in body") return status class LocationPolling(LongRunningOperation): """Implements a Location polling. """ def __init__(self): self._location_url = None def can_poll(self, pipeline_response): # type: (PipelineResponseType) -> bool """Answer if this polling method could be used. """ response = pipeline_response.http_response return "location" in response.headers def get_polling_url(self): # type: () -> str """Return the polling URL. """ return self._location_url def get_final_get_url(self, pipeline_response): # type: (PipelineResponseType) -> Optional[str] """If a final GET is needed, returns the URL. :rtype: str """ return None def set_initial_status(self, pipeline_response): # type: (PipelineResponseType) -> str """Process first response after initiating long running operation. :param azure.core.pipeline.PipelineResponse response: initial REST call response. """ response = pipeline_response.http_response self._location_url = response.headers["location"] if response.status_code in {200, 201, 202, 204} and self._location_url: return "InProgress" raise OperationFailed("Operation failed or canceled") def get_status(self, pipeline_response): # type: (PipelineResponseType) -> str """Process the latest status update retrieved from a 'location' header. :param azure.core.pipeline.PipelineResponse response: latest REST call response. :raises: BadResponse if response has no body and not status 202. """ response = pipeline_response.http_response if "location" in response.headers: self._location_url = response.headers["location"] return "InProgress" if response.status_code == 202 else "Succeeded" class StatusCheckPolling(LongRunningOperation): """Should be the fallback polling, that don't poll but exit successfully if not other polling are detected and status code is 2xx. """ def can_poll(self, pipeline_response): # type: (PipelineResponseType) -> bool """Answer if this polling method could be used. """ return True def get_polling_url(self): # type: () -> str """Return the polling URL. """ raise ValueError("This polling doesn't support polling") def set_initial_status(self, pipeline_response): # type: (PipelineResponseType) -> str """Process first response after initiating long running operation and set self.status attribute. :param azure.core.pipeline.PipelineResponse response: initial REST call response. """ return "Succeeded" def get_status(self, pipeline_response): # type: (PipelineResponseType) -> str return "Succeeded" def get_final_get_url(self, pipeline_response): # type: (PipelineResponseType) -> Optional[str] """If a final GET is needed, returns the URL. :rtype: str """ return None class LROBasePolling(PollingMethod): # pylint: disable=too-many-instance-attributes """A base LRO poller. This assumes a basic flow: - I analyze the response to decide the polling approach - I poll - I ask the final resource depending of the polling approach If your polling need are more specific, you could implement a PollingMethod directly """ def __init__( self, timeout=30, lro_algorithms=None, lro_options=None, path_format_arguments=None, **operation_config ): self._lro_algorithms = lro_algorithms or [ OperationResourcePolling(), LocationPolling(), StatusCheckPolling(), ] self._timeout = timeout self._client = None # Will hold the Pipelineclient self._operation = None # Will hold an instance of LongRunningOperation self._initial_response = None # Will hold the initial response self._pipeline_response = None # Will hold latest received response self._deserialization_callback = None # Will hold the deserialization callback self._operation_config = operation_config self._lro_options = lro_options self._path_format_arguments = path_format_arguments self._status = None def status(self): """Return the current status as a string. :rtype: str """ if not self._operation: raise ValueError( "set_initial_status was never called. Did you give this instance to a poller?" ) return self._status def finished(self): """Is this polling finished? :rtype: bool """ return _finished(self.status()) def resource(self): """Return the built resource. """ return self._parse_resource(self._pipeline_response) @property def _transport(self): return self._client._pipeline._transport # pylint: disable=protected-access def initialize(self, client, initial_response, deserialization_callback): """Set the initial status of this LRO. :param initial_response: The initial response of the poller :raises: HttpResponseError if initial status is incorrect LRO state """ self._client = client self._pipeline_response = self._initial_response = initial_response self._deserialization_callback = deserialization_callback for operation in self._lro_algorithms: if operation.can_poll(initial_response): self._operation = operation break else: raise BadResponse("Unable to find status link for polling.") try: _raise_if_bad_http_status_and_method(self._initial_response.http_response) self._status = self._operation.set_initial_status(initial_response) except BadStatus as err: self._status = "Failed" raise HttpResponseError(response=initial_response.http_response, error=err) except BadResponse as err: self._status = "Failed" raise HttpResponseError( response=initial_response.http_response, message=str(err), error=err ) except OperationFailed as err: raise HttpResponseError(response=initial_response.http_response, error=err) def get_continuation_token(self): # type() -> str import pickle return base64.b64encode(pickle.dumps(self._initial_response)).decode('ascii') @classmethod def from_continuation_token(cls, continuation_token, **kwargs): # type(str, Any) -> Tuple try: client = kwargs["client"] except KeyError: raise ValueError("Need kwarg 'client' to be recreated from continuation_token") try: deserialization_callback = kwargs["deserialization_callback"] except KeyError: raise ValueError("Need kwarg 'deserialization_callback' to be recreated from continuation_token") import pickle initial_response = pickle.loads(base64.b64decode(continuation_token)) # nosec # Restore the transport in the context initial_response.context.transport = client._pipeline._transport # pylint: disable=protected-access return client, initial_response, deserialization_callback def run(self): try: self._poll() except BadStatus as err: self._status = "Failed" raise HttpResponseError( response=self._pipeline_response.http_response, error=err ) except BadResponse as err: self._status = "Failed" raise HttpResponseError( response=self._pipeline_response.http_response, message=str(err), error=err, ) except OperationFailed as err: raise HttpResponseError( response=self._pipeline_response.http_response, error=err ) def _poll(self): """Poll status of operation so long as operation is incomplete and we have an endpoint to query. :param callable update_cmd: The function to call to retrieve the latest status of the long running operation. :raises: OperationFailed if operation status 'Failed' or 'Canceled'. :raises: BadStatus if response status invalid. :raises: BadResponse if response invalid. """ while not self.finished(): self._delay() self.update_status() if _failed(self.status()): raise OperationFailed("Operation failed or canceled") final_get_url = self._operation.get_final_get_url(self._pipeline_response) if final_get_url: self._pipeline_response = self.request_status(final_get_url) _raise_if_bad_http_status_and_method(self._pipeline_response.http_response) def _parse_resource(self, pipeline_response): # type: (PipelineResponseType) -> Optional[Any] """Assuming this response is a resource, use the deserialization callback to parse it. If body is empty, assuming no resource to return. """ response = pipeline_response.http_response if not _is_empty(response): return self._deserialization_callback(pipeline_response) return None def _sleep(self, delay): self._transport.sleep(delay) def _extract_delay(self): if self._pipeline_response is None: return None delay = get_retry_after(self._pipeline_response) if delay: return delay return self._timeout def _delay(self): """Check for a 'retry-after' header to set timeout, otherwise use configured timeout. """ delay = self._extract_delay() self._sleep(delay) def update_status(self): """Update the current status of the LRO. """ self._pipeline_response = self.request_status(self._operation.get_polling_url()) _raise_if_bad_http_status_and_method(self._pipeline_response.http_response) self._status = self._operation.get_status(self._pipeline_response) def _get_request_id(self): return self._pipeline_response.http_response.request.headers[ "x-ms-client-request-id" ] def request_status(self, status_link): """Do a simple GET to this status link. This method re-inject 'x-ms-client-request-id'. :rtype: azure.core.pipeline.PipelineResponse """ if self._path_format_arguments: status_link = self._client.format_url(status_link, **self._path_format_arguments) request = self._client.get(status_link) # Re-inject 'x-ms-client-request-id' while polling if "request_id" not in self._operation_config: self._operation_config["request_id"] = self._get_request_id() return self._client._pipeline.run( # pylint: disable=protected-access request, stream=False, **self._operation_config ) __all__ = [ 'BadResponse', 'BadStatus', 'OperationFailed', 'LongRunningOperation', 'OperationResourcePolling', 'LocationPolling', 'StatusCheckPolling', 'LROBasePolling', ]
34.057239
118
0.659219
import abc import base64 import json from typing import TYPE_CHECKING, Optional, Any, Union from ..exceptions import HttpResponseError, DecodeError from . import PollingMethod from ..pipeline.policies._utils import get_retry_after if TYPE_CHECKING: from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import ( HttpResponse, AsyncHttpResponse, HttpRequest, ) ResponseType = Union[HttpResponse, AsyncHttpResponse] PipelineResponseType = PipelineResponse[HttpRequest, ResponseType] try: ABC = abc.ABC except AttributeError: ABC = abc.ABCMeta("ABC", (object,), {"__slots__": ()}) _FINISHED = frozenset(["succeeded", "canceled", "failed"]) _FAILED = frozenset(["canceled", "failed"]) _SUCCEEDED = frozenset(["succeeded"]) def _finished(status): if hasattr(status, "value"): status = status.value return str(status).lower() in _FINISHED def _failed(status): if hasattr(status, "value"): status = status.value return str(status).lower() in _FAILED def _succeeded(status): if hasattr(status, "value"): status = status.value return str(status).lower() in _SUCCEEDED class BadStatus(Exception): pass class BadResponse(Exception): pass class OperationFailed(Exception): pass def _as_json(response): try: return json.loads(response.text()) except ValueError: raise DecodeError("Error occurred in deserializing the response body.") def _raise_if_bad_http_status_and_method(response): code = response.status_code if code in {200, 201, 202, 204}: return raise BadStatus( "Invalid return status {!r} for {!r} operation".format( code, response.request.method ) ) def _is_empty(response): return not bool(response.body()) class LongRunningOperation(ABC): @abc.abstractmethod def can_poll(self, pipeline_response): raise NotImplementedError() @abc.abstractmethod def get_polling_url(self): raise NotImplementedError() @abc.abstractmethod def set_initial_status(self, pipeline_response): raise NotImplementedError() @abc.abstractmethod def get_status(self, pipeline_response): raise NotImplementedError() @abc.abstractmethod def get_final_get_url(self, pipeline_response): raise NotImplementedError() class OperationResourcePolling(LongRunningOperation): def __init__(self, operation_location_header="operation-location"): self._operation_location_header = operation_location_header self._async_url = None self._location_url = None self._request = None def can_poll(self, pipeline_response): response = pipeline_response.http_response return self._operation_location_header in response.headers def get_polling_url(self): return self._async_url def get_final_get_url(self, pipeline_response): response = pipeline_response.http_response if not _is_empty(response): body = _as_json(response) ation = body.get("resourceLocation") if resource_location: return resource_location if self._request.method in {"PUT", "PATCH"}: return self._request.url if self._request.method == "POST" and self._location_url: return self._location_url return None def set_initial_status(self, pipeline_response): self._request = pipeline_response.http_response.request response = pipeline_response.http_response self._set_async_url_if_present(response) if response.status_code in {200, 201, 202, 204} and self._async_url: return "InProgress" raise OperationFailed("Operation failed or canceled") def _set_async_url_if_present(self, response): self._async_url = response.headers[self._operation_location_header] location_url = response.headers.get("location") if location_url: self._location_url = location_url def get_status(self, pipeline_response): response = pipeline_response.http_response if _is_empty(response): raise BadResponse( "The response from long running operation does not contain a body." ) body = _as_json(response) status = body.get("status") if not status: raise BadResponse("No status found in body") return status class LocationPolling(LongRunningOperation): def __init__(self): self._location_url = None def can_poll(self, pipeline_response): response = pipeline_response.http_response return "location" in response.headers def get_polling_url(self): return self._location_url def get_final_get_url(self, pipeline_response): return None def set_initial_status(self, pipeline_response): response = pipeline_response.http_response self._location_url = response.headers["location"] if response.status_code in {200, 201, 202, 204} and self._location_url: return "InProgress" raise OperationFailed("Operation failed or canceled") def get_status(self, pipeline_response): response = pipeline_response.http_response if "location" in response.headers: self._location_url = response.headers["location"] return "InProgress" if response.status_code == 202 else "Succeeded" class StatusCheckPolling(LongRunningOperation): def can_poll(self, pipeline_response): return True def get_polling_url(self): raise ValueError("This polling doesn't support polling") def set_initial_status(self, pipeline_response): # type: (PipelineResponseType) -> str return "Succeeded" def get_status(self, pipeline_response): # type: (PipelineResponseType) -> str return "Succeeded" def get_final_get_url(self, pipeline_response): # type: (PipelineResponseType) -> Optional[str] return None class LROBasePolling(PollingMethod): # pylint: disable=too-many-instance-attributes def __init__( self, timeout=30, lro_algorithms=None, lro_options=None, path_format_arguments=None, **operation_config ): self._lro_algorithms = lro_algorithms or [ OperationResourcePolling(), LocationPolling(), StatusCheckPolling(), ] self._timeout = timeout self._client = None # Will hold the Pipelineclient self._operation = None # Will hold an instance of LongRunningOperation self._initial_response = None # Will hold the initial response self._pipeline_response = None # Will hold latest received response self._deserialization_callback = None # Will hold the deserialization callback self._operation_config = operation_config self._lro_options = lro_options self._path_format_arguments = path_format_arguments self._status = None def status(self): if not self._operation: raise ValueError( "set_initial_status was never called. Did you give this instance to a poller?" ) return self._status def finished(self): return _finished(self.status()) def resource(self): return self._parse_resource(self._pipeline_response) @property def _transport(self): return self._client._pipeline._transport # pylint: disable=protected-access def initialize(self, client, initial_response, deserialization_callback): self._client = client self._pipeline_response = self._initial_response = initial_response self._deserialization_callback = deserialization_callback for operation in self._lro_algorithms: if operation.can_poll(initial_response): self._operation = operation break else: raise BadResponse("Unable to find status link for polling.") try: _raise_if_bad_http_status_and_method(self._initial_response.http_response) self._status = self._operation.set_initial_status(initial_response) except BadStatus as err: self._status = "Failed" raise HttpResponseError(response=initial_response.http_response, error=err) except BadResponse as err: self._status = "Failed" raise HttpResponseError( response=initial_response.http_response, message=str(err), error=err ) except OperationFailed as err: raise HttpResponseError(response=initial_response.http_response, error=err) def get_continuation_token(self): # type() -> str import pickle return base64.b64encode(pickle.dumps(self._initial_response)).decode('ascii') @classmethod def from_continuation_token(cls, continuation_token, **kwargs): # type(str, Any) -> Tuple try: client = kwargs["client"] except KeyError: raise ValueError("Need kwarg 'client' to be recreated from continuation_token") try: deserialization_callback = kwargs["deserialization_callback"] except KeyError: raise ValueError("Need kwarg 'deserialization_callback' to be recreated from continuation_token") import pickle initial_response = pickle.loads(base64.b64decode(continuation_token)) # nosec # Restore the transport in the context initial_response.context.transport = client._pipeline._transport # pylint: disable=protected-access return client, initial_response, deserialization_callback def run(self): try: self._poll() except BadStatus as err: self._status = "Failed" raise HttpResponseError( response=self._pipeline_response.http_response, error=err ) except BadResponse as err: self._status = "Failed" raise HttpResponseError( response=self._pipeline_response.http_response, message=str(err), error=err, ) except OperationFailed as err: raise HttpResponseError( response=self._pipeline_response.http_response, error=err ) def _poll(self): while not self.finished(): self._delay() self.update_status() if _failed(self.status()): raise OperationFailed("Operation failed or canceled") final_get_url = self._operation.get_final_get_url(self._pipeline_response) if final_get_url: self._pipeline_response = self.request_status(final_get_url) _raise_if_bad_http_status_and_method(self._pipeline_response.http_response) def _parse_resource(self, pipeline_response): # type: (PipelineResponseType) -> Optional[Any] response = pipeline_response.http_response if not _is_empty(response): return self._deserialization_callback(pipeline_response) return None def _sleep(self, delay): self._transport.sleep(delay) def _extract_delay(self): if self._pipeline_response is None: return None delay = get_retry_after(self._pipeline_response) if delay: return delay return self._timeout def _delay(self): delay = self._extract_delay() self._sleep(delay) def update_status(self): self._pipeline_response = self.request_status(self._operation.get_polling_url()) _raise_if_bad_http_status_and_method(self._pipeline_response.http_response) self._status = self._operation.get_status(self._pipeline_response) def _get_request_id(self): return self._pipeline_response.http_response.request.headers[ "x-ms-client-request-id" ] def request_status(self, status_link): if self._path_format_arguments: status_link = self._client.format_url(status_link, **self._path_format_arguments) request = self._client.get(status_link) # Re-inject 'x-ms-client-request-id' while polling if "request_id" not in self._operation_config: self._operation_config["request_id"] = self._get_request_id() return self._client._pipeline.run( # pylint: disable=protected-access request, stream=False, **self._operation_config ) __all__ = [ 'BadResponse', 'BadStatus', 'OperationFailed', 'LongRunningOperation', 'OperationResourcePolling', 'LocationPolling', 'StatusCheckPolling', 'LROBasePolling', ]
true
true
f72796cfdb731f2805f402a224271fe7a843f908
3,858
py
Python
tests/test_similarity.py
dhimmel/sematch
7e92b171c27a8b25e844a467554fe4bb2adfb883
[ "Apache-2.0" ]
397
2015-05-30T11:02:28.000Z
2022-03-09T01:39:31.000Z
tests/test_similarity.py
dhimmel/sematch
7e92b171c27a8b25e844a467554fe4bb2adfb883
[ "Apache-2.0" ]
32
2015-04-27T21:26:29.000Z
2021-08-19T10:20:45.000Z
tests/test_similarity.py
dhimmel/sematch
7e92b171c27a8b25e844a467554fe4bb2adfb883
[ "Apache-2.0" ]
110
2015-11-06T17:01:48.000Z
2022-02-17T05:09:02.000Z
# -*- coding: utf-8 -*- def test_word_similarity(): from sematch.semantic.similarity import WordNetSimilarity wns = WordNetSimilarity() dog = wns.word2synset('dog') cat = wns.word2synset('cat') # Measuring semantic similarity between concepts using Path method assert wns.similarity(dog[0], cat[0], 'path') is not None # 0.2 # Computing English word similarity using Li method assert wns.word_similarity('dog', 'cat', 'li') is not None# 0.449327301063 # Computing Spanish word similarity using Lin method assert wns.monol_word_similarity('perro', 'gato', 'spa', 'lin') is not None#0.876800984373 # Computing Chinese word similarity using Wu & Palmer method assert wns.monol_word_similarity('狗', '猫', 'cmn', 'wup') is not None# 0.857142857143 # Computing Spanish and English word similarity using Resnik method assert wns.crossl_word_similarity('perro', 'cat', 'spa', 'eng', 'res') is not None#7.91166650904 # Computing Spanish and Chinese word similarity using Jiang & Conrad method assert wns.crossl_word_similarity('perro', '猫', 'spa', 'cmn', 'jcn') is not None#0.31023804699 # Computing Chinese and English word similarity using WPath method assert wns.crossl_word_similarity('狗', 'cat', 'cmn', 'eng', 'wpath') is not None#0.593666388463 def test_yago_concept_similarity(): from sematch.semantic.similarity import YagoTypeSimilarity yagosim = YagoTypeSimilarity() dancer = yagosim.word2yago('dancer') actor = yagosim.word2yago('actor') singer = yagosim.word2yago('singer') assert yagosim.yago2synset(actor[0]) is not None assert yagosim.yago_similarity(dancer[0], actor[0], 'wpath') is not None assert yagosim.yago_similarity(singer[0], actor[0], 'wpath') is not None assert yagosim.word2yago('university') is not None assert yagosim.yago2synset('http://dbpedia.org/class/yago/EducationalInstitution108276342') is not None assert yagosim.yago2synset('http://dbpedia.org/class/yago/Organization108008335') is not None assert yagosim.yago2synset('http://dbpedia.org/class/yago/Institution108053576') is not None assert yagosim.yago2synset('http://dbpedia.org/class/yago/Organization108008335') is not None #using corpus-based IC from brown corpus assert yagosim.word_similarity('dancer', 'actor', 'wpath') is not None #using graph-based IC from DBpedia assert yagosim.word_similarity('dancer', 'actor', 'wpath_graph') is not None def test_dbpedia_concept_similarity(): from sematch.semantic.graph import DBpediaDataTransform, Taxonomy from sematch.semantic.similarity import ConceptSimilarity concept_sim = ConceptSimilarity(Taxonomy(DBpediaDataTransform()), 'models/dbpedia_type_ic.txt') assert concept_sim.similarity('http://dbpedia.org/ontology/Actor', 'http://dbpedia.org/ontology/Film', 'path') is not None def test_synset_expand(): from sematch.semantic.similarity import WordNetSimilarity wns = WordNetSimilarity() cat = wns.word2synset('cat')[0] assert wns.synset_expand(cat) is not None def test_entity_similarity(): from sematch.semantic.similarity import EntitySimilarity entity_sim = EntitySimilarity() assert entity_sim.similarity('http://dbpedia.org/resource/Madrid', 'http://dbpedia.org/resource/Barcelona') is not None assert entity_sim.relatedness('http://dbpedia.org/resource/Madrid', 'http://dbpedia.org/resource/Barcelona') is not None def test_language(): from sematch.semantic.similarity import WordNetSimilarity wns = WordNetSimilarity() #check the supported languages assert wns.languages() is not None #find the language code assert wns.languages('English') is not None assert wns.languages('chinese_simplified') is not None assert wns.languages('spanish') is not None
52.849315
126
0.736133
def test_word_similarity(): from sematch.semantic.similarity import WordNetSimilarity wns = WordNetSimilarity() dog = wns.word2synset('dog') cat = wns.word2synset('cat') assert wns.similarity(dog[0], cat[0], 'path') is not None assert wns.word_similarity('dog', 'cat', 'li') is not None assert wns.monol_word_similarity('perro', 'gato', 'spa', 'lin') is not None assert wns.monol_word_similarity('狗', '猫', 'cmn', 'wup') is not None assert wns.crossl_word_similarity('perro', 'cat', 'spa', 'eng', 'res') is not None assert wns.crossl_word_similarity('perro', '猫', 'spa', 'cmn', 'jcn') is not None assert wns.crossl_word_similarity('狗', 'cat', 'cmn', 'eng', 'wpath') is not None def test_yago_concept_similarity(): from sematch.semantic.similarity import YagoTypeSimilarity yagosim = YagoTypeSimilarity() dancer = yagosim.word2yago('dancer') actor = yagosim.word2yago('actor') singer = yagosim.word2yago('singer') assert yagosim.yago2synset(actor[0]) is not None assert yagosim.yago_similarity(dancer[0], actor[0], 'wpath') is not None assert yagosim.yago_similarity(singer[0], actor[0], 'wpath') is not None assert yagosim.word2yago('university') is not None assert yagosim.yago2synset('http://dbpedia.org/class/yago/EducationalInstitution108276342') is not None assert yagosim.yago2synset('http://dbpedia.org/class/yago/Organization108008335') is not None assert yagosim.yago2synset('http://dbpedia.org/class/yago/Institution108053576') is not None assert yagosim.yago2synset('http://dbpedia.org/class/yago/Organization108008335') is not None assert yagosim.word_similarity('dancer', 'actor', 'wpath') is not None assert yagosim.word_similarity('dancer', 'actor', 'wpath_graph') is not None def test_dbpedia_concept_similarity(): from sematch.semantic.graph import DBpediaDataTransform, Taxonomy from sematch.semantic.similarity import ConceptSimilarity concept_sim = ConceptSimilarity(Taxonomy(DBpediaDataTransform()), 'models/dbpedia_type_ic.txt') assert concept_sim.similarity('http://dbpedia.org/ontology/Actor', 'http://dbpedia.org/ontology/Film', 'path') is not None def test_synset_expand(): from sematch.semantic.similarity import WordNetSimilarity wns = WordNetSimilarity() cat = wns.word2synset('cat')[0] assert wns.synset_expand(cat) is not None def test_entity_similarity(): from sematch.semantic.similarity import EntitySimilarity entity_sim = EntitySimilarity() assert entity_sim.similarity('http://dbpedia.org/resource/Madrid', 'http://dbpedia.org/resource/Barcelona') is not None assert entity_sim.relatedness('http://dbpedia.org/resource/Madrid', 'http://dbpedia.org/resource/Barcelona') is not None def test_language(): from sematch.semantic.similarity import WordNetSimilarity wns = WordNetSimilarity() assert wns.languages() is not None assert wns.languages('English') is not None assert wns.languages('chinese_simplified') is not None assert wns.languages('spanish') is not None
true
true
f72797852f54a7b4a109a290c7e4ff3ec4e2193c
3,676
py
Python
src/chaospizza/orders/migrations/0001_initial.py
chaosdorf/chaospizza
6f0895f28095260d04b41a8b86edf07a87bcccb8
[ "MIT" ]
9
2017-05-19T23:32:19.000Z
2020-06-28T20:40:13.000Z
src/chaospizza/orders/migrations/0001_initial.py
step21/chaospizza
8011ebb5fd021bf74897099cedd1869bcfbd031f
[ "MIT" ]
31
2017-05-19T21:27:30.000Z
2022-01-25T21:38:13.000Z
src/chaospizza/orders/migrations/0001_initial.py
step21/chaospizza
8011ebb5fd021bf74897099cedd1869bcfbd031f
[ "MIT" ]
4
2017-05-19T23:32:05.000Z
2019-02-26T03:41:51.000Z
# Generated by Django 1.11.3 on 2017-07-07 19:21 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): # noqa initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Order', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('slug', models.SlugField()), ('coordinator', models.CharField(max_length=100)), ('restaurant_name', models.CharField(max_length=250)), ('restaurant_url', models.URLField(blank=True)), ('state', models.CharField(choices=[('preparing', 'Order is prepared, order items can be modified.'), ('ordering', 'Order is locked and sent to delivery service by coordinator.'), ('ordered', 'Order has been sent to delivery service.'), ('delivered', 'Delivery has arrived.'), ('canceled', 'Order has been canceled due to some reason.')], default='preparing', max_length=16)), ('created_at', models.DateTimeField(auto_now_add=True)), ('preparation_expires_after', models.DurationField(blank=True, help_text='How long the order is allowed to be prepared.', null=True)), ], options={ 'ordering': ('history__created_at',), }, ), migrations.CreateModel( name='OrderItem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('slug', models.SlugField()), ('participant', models.CharField(max_length=100)), ('description', models.CharField(max_length=250)), ('price', models.DecimalField(decimal_places=2, max_digits=5)), ('amount', models.PositiveIntegerField(default=1)), ('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='orders.Order')), ], ), migrations.CreateModel( name='OrderStateChange', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('old_state', models.CharField(choices=[('preparing', 'Order is prepared, order items can be modified.'), ('ordering', 'Order is locked and sent to delivery service by coordinator.'), ('ordered', 'Order has been sent to delivery service.'), ('delivered', 'Delivery has arrived.'), ('canceled', 'Order has been canceled due to some reason.')], max_length=16)), ('new_state', models.CharField(choices=[('preparing', 'Order is prepared, order items can be modified.'), ('ordering', 'Order is locked and sent to delivery service by coordinator.'), ('ordered', 'Order has been sent to delivery service.'), ('delivered', 'Delivery has arrived.'), ('canceled', 'Order has been canceled due to some reason.')], max_length=16)), ('reason', models.CharField(max_length=1000, null=True)), ('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='history', to='orders.Order')), ], ), migrations.AlterUniqueTogether( name='order', unique_together=set([('coordinator', 'restaurant_name')]), ), migrations.AlterUniqueTogether( name='orderitem', unique_together=set([('order', 'participant', 'description')]), ), ]
59.290323
392
0.612078
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Order', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('slug', models.SlugField()), ('coordinator', models.CharField(max_length=100)), ('restaurant_name', models.CharField(max_length=250)), ('restaurant_url', models.URLField(blank=True)), ('state', models.CharField(choices=[('preparing', 'Order is prepared, order items can be modified.'), ('ordering', 'Order is locked and sent to delivery service by coordinator.'), ('ordered', 'Order has been sent to delivery service.'), ('delivered', 'Delivery has arrived.'), ('canceled', 'Order has been canceled due to some reason.')], default='preparing', max_length=16)), ('created_at', models.DateTimeField(auto_now_add=True)), ('preparation_expires_after', models.DurationField(blank=True, help_text='How long the order is allowed to be prepared.', null=True)), ], options={ 'ordering': ('history__created_at',), }, ), migrations.CreateModel( name='OrderItem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('slug', models.SlugField()), ('participant', models.CharField(max_length=100)), ('description', models.CharField(max_length=250)), ('price', models.DecimalField(decimal_places=2, max_digits=5)), ('amount', models.PositiveIntegerField(default=1)), ('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='orders.Order')), ], ), migrations.CreateModel( name='OrderStateChange', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('old_state', models.CharField(choices=[('preparing', 'Order is prepared, order items can be modified.'), ('ordering', 'Order is locked and sent to delivery service by coordinator.'), ('ordered', 'Order has been sent to delivery service.'), ('delivered', 'Delivery has arrived.'), ('canceled', 'Order has been canceled due to some reason.')], max_length=16)), ('new_state', models.CharField(choices=[('preparing', 'Order is prepared, order items can be modified.'), ('ordering', 'Order is locked and sent to delivery service by coordinator.'), ('ordered', 'Order has been sent to delivery service.'), ('delivered', 'Delivery has arrived.'), ('canceled', 'Order has been canceled due to some reason.')], max_length=16)), ('reason', models.CharField(max_length=1000, null=True)), ('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='history', to='orders.Order')), ], ), migrations.AlterUniqueTogether( name='order', unique_together=set([('coordinator', 'restaurant_name')]), ), migrations.AlterUniqueTogether( name='orderitem', unique_together=set([('order', 'participant', 'description')]), ), ]
true
true
f7279801d19e14d38461c4393e790d31ce9d5df4
479
py
Python
accounting/root.py
michellab/BioSimSpaceCloud
456b146a2131565e354352872d3e75a08c3652d1
[ "Apache-2.0" ]
2
2019-02-15T16:04:19.000Z
2019-02-19T15:42:27.000Z
accounting/root.py
michellab/BioSimSpaceCloud
456b146a2131565e354352872d3e75a08c3652d1
[ "Apache-2.0" ]
null
null
null
accounting/root.py
michellab/BioSimSpaceCloud
456b146a2131565e354352872d3e75a08c3652d1
[ "Apache-2.0" ]
null
null
null
from Acquire.Service import create_return_value from Acquire.Service import get_service_info, get_service_private_key def run(args): """This function return the status and service info""" status = 0 message = None service = None service = get_service_info() status = 0 message = "Success" return_value = create_return_value(status, message) if service: return_value["service_info"] = service.to_data() return return_value
19.958333
69
0.707724
from Acquire.Service import create_return_value from Acquire.Service import get_service_info, get_service_private_key def run(args): status = 0 message = None service = None service = get_service_info() status = 0 message = "Success" return_value = create_return_value(status, message) if service: return_value["service_info"] = service.to_data() return return_value
true
true
f72798a96967ad3fd309ebf1baee8b1a120bae4d
13,803
py
Python
layers.py
richardsfc/neural_rerendering_plus
f5b2bd2ebe7e9657e3584612818eb0d137714276
[ "Apache-2.0" ]
2
2020-06-09T01:48:13.000Z
2021-07-06T11:53:51.000Z
layers.py
richardsfc/neural_rerendering_plus
f5b2bd2ebe7e9657e3584612818eb0d137714276
[ "Apache-2.0" ]
7
2020-09-26T01:11:45.000Z
2022-03-12T00:34:09.000Z
layers.py
richardsfc/neural_rerendering_plus
f5b2bd2ebe7e9657e3584612818eb0d137714276
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #     https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import functools from options import FLAGS as opts import numpy as np import tensorflow as tf from plyfile import PlyData, PlyElement class LayerDescriptor(object): def __init__(self, name, m): with tf.variable_scope(name): plydata = PlyData.read(opts.descriptor_folder + '/fused.ply') shape = [(plydata.elements[0].count // opts.descriptor_div) + 1, m] self.dim = m with tf.device('/device:GPU:1'): self.descriptors = tf.get_variable('descriptors', shape=shape) # 0 index is the null descriptor def __call__(self, x): """Apply layer to tensor x.""" with tf.device('/device:GPU:1'): shape = x.get_shape().as_list() indices = tf.reshape(x[:, :, :, -1], shape=[-1, 1]) indices = tf.compat.v1.cast(tf.math.ceil(tf.compat.v1.divide(indices, opts.descriptor_div)), tf.int64) D = tf.gather_nd(self.descriptors, indices) D = tf.reshape(D, shape=[-1, shape[1], shape[2], self.dim]) return tf.compat.v1.concat([tf.slice(x, [0, 0, 0, 0], [-1, -1, -1, opts.deep_buffer_nc]), D], axis=-1) class LayerInstanceNorm(object): def __init__(self, scope_suffix='instance_norm'): curr_scope = tf.compat.v1.get_variable_scope().name self._scope = curr_scope + '/' + scope_suffix def __call__(self, x): with tf.compat.v1.variable_scope(self._scope, reuse=tf.compat.v1.AUTO_REUSE): return tf.contrib.layers.instance_norm( x, epsilon=1e-05, center=True, scale=True) def layer_norm(x, scope='layer_norm'): return tf.contrib.layers.layer_norm(x, center=True, scale=True) def pixel_norm(x): """Pixel normalization. Args: x: 4D image tensor in B01C format. Returns: 4D tensor with pixel normalized channels. """ return x * tf.compat.v1.rsqrt(tf.compat.v1.reduce_mean(tf.compat.v1.square(x), [-1], keepdims=True) + 1e-8) def global_avg_pooling(x): return tf.compat.v1.reduce_mean(x, axis=[1, 2], keepdims=True) class FullyConnected(object): def __init__(self, n_out_units, scope_suffix='FC'): weight_init = tf.compat.v1.random_normal_initializer(mean=0., stddev=0.02) weight_regularizer = tf.contrib.layers.l2_regularizer(scale=0.0001) curr_scope = tf.get_variable_scope().name self._scope = curr_scope + '/' + scope_suffix self.fc_layer = functools.partial( tf.layers.dense, units=n_out_units, kernel_initializer=weight_init, kernel_regularizer=weight_regularizer, use_bias=True) def __call__(self, x): with tf.compat.v1.variable_scope(self._scope, reuse=tf.AUTO_REUSE): return self.fc_layer(x) def init_he_scale(shape, slope=1.0): """He neural network random normal scaling for initialization. Args: shape: list of the dimensions of the tensor. slope: float, slope of the ReLu following the layer. Returns: a float, He's standard deviation. """ fan_in = np.prod(shape[:-1]) return np.sqrt(2. / ((1. + slope**2) * fan_in)) class LayerConv(object): """Convolution layer with support for equalized learning.""" def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.): """Layer constructor. Args: name: string, layer name. w: int or 2-tuple, width of the convolution kernel. n: 2-tuple of ints, input and output channel depths. stride: int or 2-tuple, stride for the convolution kernel. padding: string, the padding method. {SAME, VALID, REFLECT}. use_scaling: bool, whether to use weight norm and scaling. relu_slope: float, the slope of the ReLu following the layer. """ assert padding in ['SAME', 'VALID', 'REFLECT'], 'Error: unsupported padding' self._padding = padding with tf.compat.v1.variable_scope(name): if isinstance(stride, int): stride = [1, stride, stride, 1] else: assert len(stride) == 2, "stride is either an int or a 2-tuple" stride = [1, stride[0], stride[1], 1] if isinstance(w, int): w = [w, w] self.w = w shape = [w[0], w[1], n[0], n[1]] init_scale, pre_scale = init_he_scale(shape, relu_slope), 1. if use_scaling: init_scale, pre_scale = pre_scale, init_scale self._stride = stride self._pre_scale = pre_scale self._weight = tf.compat.v1.get_variable( 'weight', shape=shape, initializer=tf.compat.v1.random_normal_initializer(stddev=init_scale)) self._bias = tf.compat.v1.get_variable( 'bias', shape=[n[1]], initializer=tf.compat.v1.zeros_initializer) def __call__(self, x): """Apply layer to tensor x.""" if self._padding != 'REFLECT': padding = self._padding else: padding = 'VALID' pad_top = self.w[0] // 2 pad_left = self.w[1] // 2 if (self.w[0] - self._stride[1]) % 2 == 0: pad_bottom = pad_top else: pad_bottom = self.w[0] - self._stride[1] - pad_top if (self.w[1] - self._stride[2]) % 2 == 0: pad_right = pad_left else: pad_right = self.w[1] - self._stride[2] - pad_left x = tf.compat.v1.pad(x, [[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]], mode='REFLECT') y = tf.compat.v1.nn.conv2d(x, self._weight, strides=self._stride, padding=padding) return self._pre_scale * y + self._bias class LayerTransposedConv(object): """Convolution layer with support for equalized learning.""" def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.): """Layer constructor. Args: name: string, layer name. w: int or 2-tuple, width of the convolution kernel. n: 2-tuple int, [n_in_channels, n_out_channels] stride: int or 2-tuple, stride for the convolution kernel. padding: string, the padding method {SAME, VALID, REFLECT}. use_scaling: bool, whether to use weight norm and scaling. relu_slope: float, the slope of the ReLu following the layer. """ assert padding in ['SAME'], 'Error: unsupported padding for transposed conv' if isinstance(stride, int): stride = [1, stride, stride, 1] else: assert len(stride) == 2, "stride is either an int or a 2-tuple" stride = [1, stride[0], stride[1], 1] if isinstance(w, int): w = [w, w] self.padding = padding self.nc_in, self.nc_out = n self.stride = stride with tf.variable_scope(name): kernel_shape = [w[0], w[1], self.nc_out, self.nc_in] init_scale, pre_scale = init_he_scale(kernel_shape, relu_slope), 1. if use_scaling: init_scale, pre_scale = pre_scale, init_scale self._pre_scale = pre_scale self._weight = tf.get_variable( 'weight', shape=kernel_shape, initializer=tf.random_normal_initializer(stddev=init_scale)) self._bias = tf.get_variable( 'bias', shape=[self.nc_out], initializer=tf.zeros_initializer) def __call__(self, x): """Apply layer to tensor x.""" x_shape = x.get_shape().as_list() batch_size = tf.shape(x)[0] stride_x, stride_y = self.stride[1], self.stride[2] output_shape = tf.stack([ batch_size, x_shape[1] * stride_x, x_shape[2] * stride_y, self.nc_out]) y = tf.nn.conv2d_transpose( x, filter=self._weight, output_shape=output_shape, strides=self.stride, padding=self.padding) return self._pre_scale * y + self._bias class ResBlock(object): def __init__(self, name, nc, norm_layer_constructor, activation, padding='SAME', use_scaling=False, relu_slope=1.): """Layer constructor.""" self.name = name conv2d = functools.partial( LayerConv, w=3, n=[nc, nc], stride=1, padding=padding, use_scaling=use_scaling, relu_slope=relu_slope) self.blocks = [] with tf.variable_scope(self.name): with tf.variable_scope('res0'): self.blocks.append( LayerPipe([ conv2d('res0_conv'), norm_layer_constructor('res0_norm'), activation ]) ) with tf.variable_scope('res1'): self.blocks.append( LayerPipe([ conv2d('res1_conv'), norm_layer_constructor('res1_norm') ]) ) def __call__(self, x_init): """Apply layer to tensor x.""" x = x_init for f in self.blocks: x = f(x) return x + x_init class BasicBlock(object): def __init__(self, name, n, activation=functools.partial(tf.compat.v1.nn.leaky_relu, alpha=0.2), padding='SAME', use_scaling=True, relu_slope=1.): """Layer constructor.""" self.name = name conv2d = functools.partial( LayerConv, stride=1, padding=padding, use_scaling=use_scaling, relu_slope=relu_slope) nc_in, nc_out = n # n is a 2-tuple with tf.compat.v1.variable_scope(self.name): self.path1_blocks = [] with tf.compat.v1.variable_scope('bb_path1'): self.path1_blocks.append( LayerPipe([ activation, conv2d('bb_conv0', w=3, n=[nc_in, nc_out]), activation, conv2d('bb_conv1', w=3, n=[nc_out, nc_out]), downscale ]) ) self.path2_blocks = [] with tf.compat.v1.variable_scope('bb_path2'): self.path2_blocks.append( LayerPipe([ downscale, conv2d('path2_conv', w=1, n=[nc_in, nc_out]) ]) ) def __call__(self, x_init): """Apply layer to tensor x.""" x1 = x_init x2 = x_init for f in self.path1_blocks: x1 = f(x1) for f in self.path2_blocks: x2 = f(x2) return x1 + x2 class LayerDense(object): """Dense layer with a non-linearity.""" def __init__(self, name, n, use_scaling=False, relu_slope=1.): """Layer constructor. Args: name: string, layer name. n: 2-tuple of ints, input and output widths. use_scaling: bool, whether to use weight norm and scaling. relu_slope: float, the slope of the ReLu following the layer. """ with tf.variable_scope(name): init_scale, pre_scale = init_he_scale(n, relu_slope), 1. if use_scaling: init_scale, pre_scale = pre_scale, init_scale self._pre_scale = pre_scale self._weight = tf.get_variable( 'weight', shape=n, initializer=tf.random_normal_initializer(stddev=init_scale)) self._bias = tf.get_variable( 'bias', shape=[n[1]], initializer=tf.zeros_initializer) def __call__(self, x): """Apply layer to tensor x.""" return self._pre_scale * tf.matmul(x, self._weight) + self._bias class LayerPipe(object): """Pipe a sequence of functions.""" def __init__(self, functions): """Layer constructor. Args: functions: list, functions to pipe. """ self._functions = tuple(functions) def __call__(self, x, **kwargs): """Apply pipe to tensor x and return result.""" del kwargs for f in self._functions: x = f(x) return x def downscale(x, n=2): """Box downscaling. Args: x: 4D image tensor. n: integer scale (must be a power of 2). Returns: 4D tensor of images down scaled by a factor n. """ if n == 1: return x return tf.compat.v1.nn.avg_pool(x, [1, n, n, 1], [1, n, n, 1], 'VALID') def upscale(x, n): """Box upscaling (also called nearest neighbors). Args: x: 4D image tensor in B01C format. n: integer scale (must be a power of 2). Returns: 4D tensor of images up scaled by a factor n. """ if n == 1: return x x_shape = tf.compat.v1.shape(x) height, width = x_shape[1], x_shape[2] return tf.compat.v1.image.resize_nearest_neighbor(x, [n * height, n * width]) def tile_and_concatenate(x, z, n_z): z = tf.compat.v1.reshape(z, shape=[-1, 1, 1, n_z]) z = tf.compat.v1.tile(z, [1, tf.compat.v1.shape(x)[1], tf.compat.v1.shape(x)[2], 1]) x = tf.compat.v1.concat([x, z], axis=-1) return x def minibatch_mean_variance(x): """Computes the variance average. This is used by the discriminator as a form of batch discrimination. Args: x: nD tensor for which to compute variance average. Returns: a scalar, the mean variance of variable x. """ mean = tf.compat.v1.reduce_mean(x, 0, keepdims=True) vals = tf.compat.v1.sqrt(tf.compat.v1.reduce_mean(tf.compat.v1.squared_difference(x, mean), 0) + 1e-8) vals = tf.compat.v1.reduce_mean(vals) return vals def scalar_concat(x, scalar): """Concatenate a scalar to a 4D tensor as an extra channel. Args: x: 4D image tensor in B01C format. scalar: a scalar to concatenate to the tensor. Returns: a 4D tensor with one extra channel containing the value scalar at every position. """ s = tf.compat.v1.shape(x) return tf.compat.v1.concat([x, tf.compat.v1.ones([s[0], s[1], s[2], 1]) * scalar], axis=3)
31.658257
110
0.626096
import functools from options import FLAGS as opts import numpy as np import tensorflow as tf from plyfile import PlyData, PlyElement class LayerDescriptor(object): def __init__(self, name, m): with tf.variable_scope(name): plydata = PlyData.read(opts.descriptor_folder + '/fused.ply') shape = [(plydata.elements[0].count // opts.descriptor_div) + 1, m] self.dim = m with tf.device('/device:GPU:1'): self.descriptors = tf.get_variable('descriptors', shape=shape) def __call__(self, x): with tf.device('/device:GPU:1'): shape = x.get_shape().as_list() indices = tf.reshape(x[:, :, :, -1], shape=[-1, 1]) indices = tf.compat.v1.cast(tf.math.ceil(tf.compat.v1.divide(indices, opts.descriptor_div)), tf.int64) D = tf.gather_nd(self.descriptors, indices) D = tf.reshape(D, shape=[-1, shape[1], shape[2], self.dim]) return tf.compat.v1.concat([tf.slice(x, [0, 0, 0, 0], [-1, -1, -1, opts.deep_buffer_nc]), D], axis=-1) class LayerInstanceNorm(object): def __init__(self, scope_suffix='instance_norm'): curr_scope = tf.compat.v1.get_variable_scope().name self._scope = curr_scope + '/' + scope_suffix def __call__(self, x): with tf.compat.v1.variable_scope(self._scope, reuse=tf.compat.v1.AUTO_REUSE): return tf.contrib.layers.instance_norm( x, epsilon=1e-05, center=True, scale=True) def layer_norm(x, scope='layer_norm'): return tf.contrib.layers.layer_norm(x, center=True, scale=True) def pixel_norm(x): return x * tf.compat.v1.rsqrt(tf.compat.v1.reduce_mean(tf.compat.v1.square(x), [-1], keepdims=True) + 1e-8) def global_avg_pooling(x): return tf.compat.v1.reduce_mean(x, axis=[1, 2], keepdims=True) class FullyConnected(object): def __init__(self, n_out_units, scope_suffix='FC'): weight_init = tf.compat.v1.random_normal_initializer(mean=0., stddev=0.02) weight_regularizer = tf.contrib.layers.l2_regularizer(scale=0.0001) curr_scope = tf.get_variable_scope().name self._scope = curr_scope + '/' + scope_suffix self.fc_layer = functools.partial( tf.layers.dense, units=n_out_units, kernel_initializer=weight_init, kernel_regularizer=weight_regularizer, use_bias=True) def __call__(self, x): with tf.compat.v1.variable_scope(self._scope, reuse=tf.AUTO_REUSE): return self.fc_layer(x) def init_he_scale(shape, slope=1.0): fan_in = np.prod(shape[:-1]) return np.sqrt(2. / ((1. + slope**2) * fan_in)) class LayerConv(object): def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.): assert padding in ['SAME', 'VALID', 'REFLECT'], 'Error: unsupported padding' self._padding = padding with tf.compat.v1.variable_scope(name): if isinstance(stride, int): stride = [1, stride, stride, 1] else: assert len(stride) == 2, "stride is either an int or a 2-tuple" stride = [1, stride[0], stride[1], 1] if isinstance(w, int): w = [w, w] self.w = w shape = [w[0], w[1], n[0], n[1]] init_scale, pre_scale = init_he_scale(shape, relu_slope), 1. if use_scaling: init_scale, pre_scale = pre_scale, init_scale self._stride = stride self._pre_scale = pre_scale self._weight = tf.compat.v1.get_variable( 'weight', shape=shape, initializer=tf.compat.v1.random_normal_initializer(stddev=init_scale)) self._bias = tf.compat.v1.get_variable( 'bias', shape=[n[1]], initializer=tf.compat.v1.zeros_initializer) def __call__(self, x): if self._padding != 'REFLECT': padding = self._padding else: padding = 'VALID' pad_top = self.w[0] // 2 pad_left = self.w[1] // 2 if (self.w[0] - self._stride[1]) % 2 == 0: pad_bottom = pad_top else: pad_bottom = self.w[0] - self._stride[1] - pad_top if (self.w[1] - self._stride[2]) % 2 == 0: pad_right = pad_left else: pad_right = self.w[1] - self._stride[2] - pad_left x = tf.compat.v1.pad(x, [[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]], mode='REFLECT') y = tf.compat.v1.nn.conv2d(x, self._weight, strides=self._stride, padding=padding) return self._pre_scale * y + self._bias class LayerTransposedConv(object): def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.): assert padding in ['SAME'], 'Error: unsupported padding for transposed conv' if isinstance(stride, int): stride = [1, stride, stride, 1] else: assert len(stride) == 2, "stride is either an int or a 2-tuple" stride = [1, stride[0], stride[1], 1] if isinstance(w, int): w = [w, w] self.padding = padding self.nc_in, self.nc_out = n self.stride = stride with tf.variable_scope(name): kernel_shape = [w[0], w[1], self.nc_out, self.nc_in] init_scale, pre_scale = init_he_scale(kernel_shape, relu_slope), 1. if use_scaling: init_scale, pre_scale = pre_scale, init_scale self._pre_scale = pre_scale self._weight = tf.get_variable( 'weight', shape=kernel_shape, initializer=tf.random_normal_initializer(stddev=init_scale)) self._bias = tf.get_variable( 'bias', shape=[self.nc_out], initializer=tf.zeros_initializer) def __call__(self, x): x_shape = x.get_shape().as_list() batch_size = tf.shape(x)[0] stride_x, stride_y = self.stride[1], self.stride[2] output_shape = tf.stack([ batch_size, x_shape[1] * stride_x, x_shape[2] * stride_y, self.nc_out]) y = tf.nn.conv2d_transpose( x, filter=self._weight, output_shape=output_shape, strides=self.stride, padding=self.padding) return self._pre_scale * y + self._bias class ResBlock(object): def __init__(self, name, nc, norm_layer_constructor, activation, padding='SAME', use_scaling=False, relu_slope=1.): self.name = name conv2d = functools.partial( LayerConv, w=3, n=[nc, nc], stride=1, padding=padding, use_scaling=use_scaling, relu_slope=relu_slope) self.blocks = [] with tf.variable_scope(self.name): with tf.variable_scope('res0'): self.blocks.append( LayerPipe([ conv2d('res0_conv'), norm_layer_constructor('res0_norm'), activation ]) ) with tf.variable_scope('res1'): self.blocks.append( LayerPipe([ conv2d('res1_conv'), norm_layer_constructor('res1_norm') ]) ) def __call__(self, x_init): x = x_init for f in self.blocks: x = f(x) return x + x_init class BasicBlock(object): def __init__(self, name, n, activation=functools.partial(tf.compat.v1.nn.leaky_relu, alpha=0.2), padding='SAME', use_scaling=True, relu_slope=1.): self.name = name conv2d = functools.partial( LayerConv, stride=1, padding=padding, use_scaling=use_scaling, relu_slope=relu_slope) nc_in, nc_out = n with tf.compat.v1.variable_scope(self.name): self.path1_blocks = [] with tf.compat.v1.variable_scope('bb_path1'): self.path1_blocks.append( LayerPipe([ activation, conv2d('bb_conv0', w=3, n=[nc_in, nc_out]), activation, conv2d('bb_conv1', w=3, n=[nc_out, nc_out]), downscale ]) ) self.path2_blocks = [] with tf.compat.v1.variable_scope('bb_path2'): self.path2_blocks.append( LayerPipe([ downscale, conv2d('path2_conv', w=1, n=[nc_in, nc_out]) ]) ) def __call__(self, x_init): x1 = x_init x2 = x_init for f in self.path1_blocks: x1 = f(x1) for f in self.path2_blocks: x2 = f(x2) return x1 + x2 class LayerDense(object): def __init__(self, name, n, use_scaling=False, relu_slope=1.): with tf.variable_scope(name): init_scale, pre_scale = init_he_scale(n, relu_slope), 1. if use_scaling: init_scale, pre_scale = pre_scale, init_scale self._pre_scale = pre_scale self._weight = tf.get_variable( 'weight', shape=n, initializer=tf.random_normal_initializer(stddev=init_scale)) self._bias = tf.get_variable( 'bias', shape=[n[1]], initializer=tf.zeros_initializer) def __call__(self, x): return self._pre_scale * tf.matmul(x, self._weight) + self._bias class LayerPipe(object): def __init__(self, functions): self._functions = tuple(functions) def __call__(self, x, **kwargs): del kwargs for f in self._functions: x = f(x) return x def downscale(x, n=2): if n == 1: return x return tf.compat.v1.nn.avg_pool(x, [1, n, n, 1], [1, n, n, 1], 'VALID') def upscale(x, n): if n == 1: return x x_shape = tf.compat.v1.shape(x) height, width = x_shape[1], x_shape[2] return tf.compat.v1.image.resize_nearest_neighbor(x, [n * height, n * width]) def tile_and_concatenate(x, z, n_z): z = tf.compat.v1.reshape(z, shape=[-1, 1, 1, n_z]) z = tf.compat.v1.tile(z, [1, tf.compat.v1.shape(x)[1], tf.compat.v1.shape(x)[2], 1]) x = tf.compat.v1.concat([x, z], axis=-1) return x def minibatch_mean_variance(x): mean = tf.compat.v1.reduce_mean(x, 0, keepdims=True) vals = tf.compat.v1.sqrt(tf.compat.v1.reduce_mean(tf.compat.v1.squared_difference(x, mean), 0) + 1e-8) vals = tf.compat.v1.reduce_mean(vals) return vals def scalar_concat(x, scalar): s = tf.compat.v1.shape(x) return tf.compat.v1.concat([x, tf.compat.v1.ones([s[0], s[1], s[2], 1]) * scalar], axis=3)
true
true
f7279945818ccb74868b87f76d1ec78f62a9ecf6
536
py
Python
pysql/__init__.py
fossabot/PySQL
3cd46130ce12bcd7636d4715176d6610b1dcf279
[ "MIT" ]
12
2021-03-12T12:12:02.000Z
2021-10-04T18:30:19.000Z
pysql/__init__.py
fossabot/PySQL
3cd46130ce12bcd7636d4715176d6610b1dcf279
[ "MIT" ]
28
2021-03-14T05:52:36.000Z
2022-03-17T04:16:28.000Z
pysql/__init__.py
fossabot/PySQL
3cd46130ce12bcd7636d4715176d6610b1dcf279
[ "MIT" ]
8
2021-03-31T14:31:49.000Z
2022-03-13T09:43:31.000Z
""" module for PySQL wrapper functions, for using as a library """ __author__ = "Devansh Singh" __email__ = "devanshamity@gmail.com" __license__ = "MIT" from pysql import * """ classes for functions for initializing object instances, use (username, password) of local MySQL server """ from pysql.packages.auth import Database from pysql.packages.ddl_commands import DDL, Alter from pysql.packages.dml_commands import DML from pysql.data.export import Export from pysql.data.imports import Import """ PySQL Devansh Singh, 2021 """
17.290323
50
0.772388
__author__ = "Devansh Singh" __email__ = "devanshamity@gmail.com" __license__ = "MIT" from pysql import * from pysql.packages.auth import Database from pysql.packages.ddl_commands import DDL, Alter from pysql.packages.dml_commands import DML from pysql.data.export import Export from pysql.data.imports import Import
true
true
f72799e9e1cbfc52c99b8a8ba84b5bcb51232a74
982
py
Python
setup.py
AndreJambersi/Project_hours
3f99566e0b1e54aa4e2f848ad34dbe9988f75591
[ "MIT" ]
1
2019-10-23T17:38:07.000Z
2019-10-23T17:38:07.000Z
setup.py
AndreJambersi/TimeBetweenBusinessHours
3f99566e0b1e54aa4e2f848ad34dbe9988f75591
[ "MIT" ]
null
null
null
setup.py
AndreJambersi/TimeBetweenBusinessHours
3f99566e0b1e54aa4e2f848ad34dbe9988f75591
[ "MIT" ]
null
null
null
from distutils.core import setup setup( name = 'TimeBetweenBusinessHours', packages = ['TimeBetweenBusinessHours'], version = '0.1', license='MIT', description = 'Get the Time Between Business Hours', author = 'AndreJambersi', author_email = 'andrejambersi@gmail.com', url = 'https://github.com/AndreJambersi/TimeBetweenBusinessHours', download_url = 'https://github.com/AndreJambersi/TimeBetweenBusinessHours/archive/v_01.tar.gz', keywords = ['JOB', 'TIME', 'DATE'], install_requires=[ 'TimeBetweenBusinessHours', 'datetime', ], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
35.071429
98
0.645621
from distutils.core import setup setup( name = 'TimeBetweenBusinessHours', packages = ['TimeBetweenBusinessHours'], version = '0.1', license='MIT', description = 'Get the Time Between Business Hours', author = 'AndreJambersi', author_email = 'andrejambersi@gmail.com', url = 'https://github.com/AndreJambersi/TimeBetweenBusinessHours', download_url = 'https://github.com/AndreJambersi/TimeBetweenBusinessHours/archive/v_01.tar.gz', keywords = ['JOB', 'TIME', 'DATE'], install_requires=[ 'TimeBetweenBusinessHours', 'datetime', ], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
true
true
f7279c891026d6d9c304e4c395e6d04dfac0fd5f
44,050
py
Python
TexSoup/data.py
pablo-angulo/TexSoup
bfd09bcfc8e020f26939a7166d9316bac51515f0
[ "BSD-2-Clause" ]
190
2016-09-26T08:38:31.000Z
2022-02-10T23:18:00.000Z
TexSoup/data.py
pablo-angulo/TexSoup
bfd09bcfc8e020f26939a7166d9316bac51515f0
[ "BSD-2-Clause" ]
127
2016-05-20T07:31:06.000Z
2022-02-16T14:48:09.000Z
TexSoup/data.py
pablo-angulo/TexSoup
bfd09bcfc8e020f26939a7166d9316bac51515f0
[ "BSD-2-Clause" ]
44
2017-07-23T19:58:00.000Z
2021-12-03T12:57:48.000Z
"""TexSoup transforms a LaTeX document into a complex tree of various Python objects, but all objects fall into one of the following three categories: ``TexNode``, ``TexExpr`` (environments and commands), and ``TexGroup`` s. """ import itertools import re from TexSoup.utils import CharToLineOffset, Token, TC, to_list __all__ = ['TexNode', 'TexCmd', 'TexEnv', 'TexGroup', 'BracketGroup', 'BraceGroup', 'TexArgs', 'TexText', 'TexMathEnv', 'TexDisplayMathEnv', 'TexNamedEnv', 'TexMathModeEnv', 'TexDisplayMathModeEnv'] ############# # Interface # ############# class TexNode(object): r"""A tree node representing an expression in the LaTeX document. Every node in the parse tree is a ``TexNode``, equipped with navigation, search, and modification utilities. To navigate the parse tree, use abstractions such as ``children`` and ``descendant``. To access content in the parse tree, use abstractions such as ``contents``, ``text``, ``string`` , and ``args``. Note that the LaTeX parse tree is largely shallow: only environments such as ``itemize`` or ``enumerate`` have children and thus descendants. Typical LaTeX expressions such as ``\section`` have *arguments* but not children. """ def __init__(self, expr, src=None): """Creates TexNode object. :param TexExpr expr: a LaTeX expression, either a singleton command or an environment containing other commands :param str src: LaTeX source string """ assert isinstance(expr, TexExpr), \ 'Expression given to node must be a valid TexExpr' super().__init__() self.expr = expr self.parent = None if src is not None: self.char_to_line = CharToLineOffset(src) else: self.char_to_line = None ################# # MAGIC METHODS # ################# def __contains__(self, other): """Use custom containment checker where applicable (TexText, for ex)""" if hasattr(self.expr, '__contains__'): return other in self.expr return other in iter(self) def __getattr__(self, attr, default=None): """Convert all invalid attributes into basic find operation.""" return self.find(attr) or default def __getitem__(self, item): return list(self.contents)[item] def __iter__(self): """ >>> node = TexNode(TexNamedEnv('lstlisting', ('hai', 'there'))) >>> list(node) ['hai', 'there'] """ return iter(self.contents) def __match__(self, name=None, attrs=()): r"""Check if given attributes match current object >>> from TexSoup import TexSoup >>> soup = TexSoup(r'\ref{hello}\ref{hello}\ref{hello}\ref{nono}') >>> soup.count(r'\ref{hello}') 3 """ return self.expr.__match__(name, attrs) def __repr__(self): """Interpreter representation.""" return str(self) def __str__(self): """Stringified command.""" return str(self.expr) ############## # PROPERTIES # ############## @property @to_list def all(self): r"""Returns all content in this node, regardless of whitespace or not. This includes all LaTeX needed to reconstruct the original source. >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \newcommand{reverseconcat}[3]{#3#2#1} ... ''') >>> alls = soup.all >>> alls[0] <BLANKLINE> <BLANKLINE> >>> alls[1] \newcommand{reverseconcat}[3]{#3#2#1} """ for child in self.expr.all: assert isinstance(child, TexExpr) node = TexNode(child) node.parent = self yield node @property def args(self): r"""Arguments for this node. Note that this argument is settable. :rtype: TexArgs >>> from TexSoup import TexSoup >>> soup = TexSoup(r'''\newcommand{reverseconcat}[3]{#3#2#1}''') >>> soup.newcommand.args [BraceGroup('reverseconcat'), BracketGroup('3'), BraceGroup('#3#2#1')] >>> soup.newcommand.args = soup.newcommand.args[:2] >>> soup.newcommand \newcommand{reverseconcat}[3] """ return self.expr.args @args.setter def args(self, args): assert isinstance(args, TexArgs), "`args` must be of type `TexArgs`" self.expr.args = args @property @to_list def children(self): r"""Immediate children of this TeX element that are valid TeX objects. This is equivalent to contents, excluding text elements and keeping only Tex expressions. :return: generator of all children :rtype: Iterator[TexExpr] >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... Random text! ... \item Hello ... \end{itemize}''') >>> soup.itemize.children[0] \item Hello <BLANKLINE> """ for child in self.expr.children: node = TexNode(child) node.parent = self yield node @property @to_list def contents(self): r"""Any non-whitespace contents inside of this TeX element. :return: generator of all nodes, tokens, and strings :rtype: Iterator[Union[TexNode,str]] >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... Random text! ... \item Hello ... \end{itemize}''') >>> contents = soup.itemize.contents >>> contents[0] '\n Random text!\n ' >>> contents[1] \item Hello <BLANKLINE> """ for child in self.expr.contents: if isinstance(child, TexExpr): node = TexNode(child) node.parent = self yield node else: yield child @contents.setter def contents(self, contents): self.expr.contents = contents @property def descendants(self): r"""Returns all descendants for this TeX element. >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... \begin{itemize} ... \item Nested ... \end{itemize} ... \end{itemize}''') >>> descendants = list(soup.itemize.descendants) >>> descendants[1] \item Nested <BLANKLINE> """ return self.__descendants() @property def name(self): r"""Name of the expression. Used for search functions. :rtype: str >>> from TexSoup import TexSoup >>> soup = TexSoup(r'''\textbf{Hello}''') >>> soup.textbf.name 'textbf' >>> soup.textbf.name = 'textit' >>> soup.textit \textit{Hello} """ return self.expr.name @name.setter def name(self, name): self.expr.name = name @property def string(self): r"""This is valid if and only if 1. the expression is a :class:`.TexCmd` AND has only one argument OR 2. the expression is a :class:`.TexEnv` AND has only one TexText child :rtype: Union[None,str] >>> from TexSoup import TexSoup >>> soup = TexSoup(r'''\textbf{Hello}''') >>> soup.textbf.string 'Hello' >>> soup.textbf.string = 'Hello World' >>> soup.textbf.string 'Hello World' >>> soup.textbf \textbf{Hello World} >>> soup = TexSoup(r'''\begin{equation}1+1\end{equation}''') >>> soup.equation.string '1+1' >>> soup.equation.string = '2+2' >>> soup.equation.string '2+2' """ if isinstance(self.expr, TexCmd): assert len(self.expr.args) == 1, \ '.string is only valid for commands with one argument' return self.expr.args[0].string contents = list(self.contents) if isinstance(self.expr, TexEnv): assert len(contents) == 1 and \ isinstance(contents[0], (TexText, str)), \ '.string is only valid for environments with only text content' return contents[0] @string.setter def string(self, string): if isinstance(self.expr, TexCmd): assert len(self.expr.args) == 1, \ '.string is only valid for commands with one argument' self.expr.args[0].string = string contents = list(self.contents) if isinstance(self.expr, TexEnv): assert len(contents) == 1 and \ isinstance(contents[0], (TexText, str)), \ '.string is only valid for environments with only text content' self.contents = [string] @property def position(self): r"""Position of first character in expression, in original source. Note this position is NOT updated as the parsed tree is modified. """ return self.expr.position @property @to_list def text(self): r"""All text in descendant nodes. This is equivalent to contents, keeping text elements and excluding Tex expressions. >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... \begin{itemize} ... \item Nested ... \end{itemize} ... \end{itemize}''') >>> soup.text[0] ' Nested\n ' """ for descendant in self.contents: if isinstance(descendant, (TexText, Token)): yield descendant elif hasattr(descendant, 'text'): yield from descendant.text ################## # PUBLIC METHODS # ################## def append(self, *nodes): r"""Add node(s) to this node's list of children. :param TexNode nodes: List of nodes to add >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... \item Hello ... \end{itemize} ... \section{Hey} ... \textit{Willy}''') >>> soup.section \section{Hey} >>> soup.section.append(soup.textit) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: ... >>> soup.section \section{Hey} >>> soup.itemize.append(' ', soup.item) >>> soup.itemize \begin{itemize} \item Hello \item Hello \end{itemize} """ self.expr.append(*nodes) def insert(self, i, *nodes): r"""Add node(s) to this node's list of children, at position i. :param int i: Position to add nodes to :param TexNode nodes: List of nodes to add >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... \item Hello ... \item Bye ... \end{itemize}''') >>> item = soup.item.copy() >>> soup.item.delete() >>> soup.itemize.insert(1, item) >>> soup.itemize \begin{itemize} \item Hello \item Bye \end{itemize} >>> item.parent.name == soup.itemize.name True """ assert isinstance(i, int), ( 'Provided index "{}" is not an integer! Did you switch your ' 'arguments? The first argument to `insert` is the ' 'index.'.format(i)) for node in nodes: if not isinstance(node, TexNode): continue assert not node.parent, ( 'Inserted node should not already have parent. Call `.copy()` ' 'on node to fix.' ) node.parent = self self.expr.insert(i, *nodes) def char_pos_to_line(self, char_pos): r"""Map position in the original string to parsed LaTeX position. :param int char_pos: Character position in the original string :return: (line number, index of character in line) :rtype: Tuple[int, int] >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \section{Hey} ... \textbf{Silly} ... \textit{Willy}''') >>> soup.char_pos_to_line(10) (1, 9) >>> soup.char_pos_to_line(20) (2, 5) """ assert self.char_to_line is not None, ( 'CharToLineOffset is not initialized. Pass src to TexNode ' 'constructor') return self.char_to_line(char_pos) def copy(self): r"""Create another copy of the current node. >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \section{Hey} ... \textit{Silly} ... \textit{Willy}''') >>> s = soup.section.copy() >>> s.parent is None True """ return TexNode(self.expr) def count(self, name=None, **attrs): r"""Number of descendants matching criteria. :param Union[None,str] name: name of LaTeX expression :param attrs: LaTeX expression attributes, such as item text. :return: number of matching expressions :rtype: int >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \section{Hey} ... \textit{Silly} ... \textit{Willy}''') >>> soup.count('section') 1 >>> soup.count('textit') 2 """ return len(list(self.find_all(name, **attrs))) def delete(self): r"""Delete this node from the parse tree. Where applicable, this will remove all descendants of this node from the parse tree. >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \textit{\color{blue}{Silly}}\textit{keep me!}''') >>> soup.textit.color.delete() >>> soup <BLANKLINE> \textit{}\textit{keep me!} >>> soup.textit.delete() >>> soup <BLANKLINE> \textit{keep me!} """ # TODO: needs better abstraction for supports contents parent = self.parent if parent.expr._supports_contents(): parent.remove(self) return # TODO: needs abstraction for removing from arg for arg in parent.args: if self.expr in arg.contents: arg._contents.remove(self.expr) def find(self, name=None, **attrs): r"""First descendant node matching criteria. Returns None if no descendant node found. :return: descendant node matching criteria :rtype: Union[None,TexExpr] >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \section{Ooo} ... \textit{eee} ... \textit{ooo}''') >>> soup.find('textit') \textit{eee} >>> soup.find('textbf') """ try: return self.find_all(name, **attrs)[0] except IndexError: return None @to_list def find_all(self, name=None, **attrs): r"""Return all descendant nodes matching criteria. :param Union[None,str,list] name: name of LaTeX expression :param attrs: LaTeX expression attributes, such as item text. :return: All descendant nodes matching criteria :rtype: Iterator[TexNode] If `name` is a list of `str`'s, any matching section will be matched. >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \section{Ooo} ... \textit{eee} ... \textit{ooo}''') >>> gen = soup.find_all('textit') >>> gen[0] \textit{eee} >>> gen[1] \textit{ooo} >>> soup.find_all('textbf')[0] Traceback (most recent call last): ... IndexError: list index out of range """ for descendant in self.__descendants(): if hasattr(descendant, '__match__') and \ descendant.__match__(name, attrs): yield descendant def remove(self, node): r"""Remove a node from this node's list of contents. :param TexExpr node: Node to remove >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... \item Hello ... \item Bye ... \end{itemize}''') >>> soup.itemize.remove(soup.item) >>> soup.itemize \begin{itemize} \item Bye \end{itemize} """ self.expr.remove(node.expr) def replace_with(self, *nodes): r"""Replace this node in the parse tree with the provided node(s). :param TexNode nodes: List of nodes to subtitute in >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... \item Hello ... \item Bye ... \end{itemize}''') >>> items = list(soup.find_all('item')) >>> bye = items[1] >>> soup.item.replace_with(bye) >>> soup.itemize \begin{itemize} \item Bye \item Bye \end{itemize} """ self.parent.replace(self, *nodes) def replace(self, child, *nodes): r"""Replace provided node with node(s). :param TexNode child: Child node to replace :param TexNode nodes: List of nodes to subtitute in >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... \item Hello ... \item Bye ... \end{itemize}''') >>> items = list(soup.find_all('item')) >>> bye = items[1] >>> soup.itemize.replace(soup.item, bye) >>> soup.itemize \begin{itemize} \item Bye \item Bye \end{itemize} """ self.expr.insert( self.expr.remove(child.expr), *nodes) def search_regex(self, pattern): for node in self.text: for match in re.finditer(pattern, node): body = match.group() # group() returns the full match start = match.start() yield Token(body, node.position + start) def __descendants(self): """Implementation for descendants, hacky workaround for __getattr__ issues.""" return itertools.chain(self.contents, *[c.descendants for c in self.children]) ############### # Expressions # ############### class TexExpr(object): """General abstraction for a TeX expression. An expression may be a command or an environment and is identified by a name, arguments, and place in the parse tree. This is an abstract and is not directly instantiated. """ def __init__(self, name, contents=(), args=(), preserve_whitespace=False, position=-1): """Initialize a tex expression. :param str name: name of environment :param iterable contents: list of contents :param iterable args: list of Tex Arguments :param bool preserve_whitespace: If false, elements containing only whitespace will be removed from contents. :param int position: position of first character in original source """ self.name = name.strip() # TODO: should not ever have space self.args = TexArgs(args) self.parent = None self._contents = list(contents) or [] self.preserve_whitespace = preserve_whitespace self.position = position for content in contents: if isinstance(content, (TexEnv, TexCmd)): content.parent = self ################# # MAGIC METHODS # ################# def __eq__(self, other): """Check if two expressions are equal. This is useful when defining data structures over TexExprs. >>> exprs = [ ... TexExpr('cake', ['flour', 'taro']), ... TexExpr('corgi', ['derp', 'collar', 'drool', 'sass']) ... ] >>> exprs[0] in exprs True >>> TexExpr('cake', ['flour', 'taro']) in exprs True """ return str(other) == str(self) def __match__(self, name=None, attrs=()): """Check if given attributes match current object.""" # TODO: this should re-parse the name, instead of hardcoding here if '{' in name or '[' in name: return str(self) == name if isinstance(name, list): node_name = getattr(self, 'name') if node_name not in name: return False else: attrs['name'] = name for k, v in attrs.items(): if getattr(self, k) != v: return False return True def __repr__(self): if not self.args: return "TexExpr('%s', %s)" % (self.name, repr(self._contents)) return "TexExpr('%s', %s, %s)" % ( self.name, repr(self._contents), repr(self.args)) ############## # PROPERTIES # ############## @property @to_list def all(self): r"""Returns all content in this expression, regardless of whitespace or not. This includes all LaTeX needed to reconstruct the original source. >>> expr1 = TexExpr('textbf', ('\n', 'hi')) >>> expr2 = TexExpr('textbf', ('\n', 'hi'), preserve_whitespace=True) >>> list(expr1.all) == list(expr2.all) True """ for arg in self.args: for expr in arg.contents: yield expr for content in self._contents: yield content @property @to_list def children(self): return filter(lambda x: isinstance(x, (TexEnv, TexCmd)), self.contents) @property @to_list def contents(self): r"""Returns all contents in this expression. Optionally includes whitespace if set when node was created. >>> expr1 = TexExpr('textbf', ('\n', 'hi')) >>> list(expr1.contents) ['hi'] >>> expr2 = TexExpr('textbf', ('\n', 'hi'), preserve_whitespace=True) >>> list(expr2.contents) ['\n', 'hi'] >>> expr = TexExpr('textbf', ('\n', 'hi')) >>> expr.contents = ('hehe', '👻') >>> list(expr.contents) ['hehe', '👻'] >>> expr.contents = 35 #doctest:+ELLIPSIS Traceback (most recent call last): ... TypeError: ... """ for content in self.all: if isinstance(content, TexText): content = content._text is_whitespace = isinstance(content, str) and content.isspace() if not is_whitespace or self.preserve_whitespace: yield content @contents.setter def contents(self, contents): if not isinstance(contents, (list, tuple)) or not all( isinstance(content, (str, TexExpr)) for content in contents): raise TypeError( '.contents value "%s" must be a list or tuple of strings or ' 'TexExprs' % contents) _contents = [TexText(c) if isinstance(c, str) else c for c in contents] self._contents = _contents @property def string(self): """All contents stringified. A convenience property >>> expr = TexExpr('hello', ['naw']) >>> expr.string 'naw' >>> expr.string = 'huehue' >>> expr.string 'huehue' >>> type(expr.string) <class 'TexSoup.data.TexText'> >>> str(expr) "TexExpr('hello', ['huehue'])" >>> expr.string = 35 #doctest:+ELLIPSIS Traceback (most recent call last): ... TypeError: ... """ return TexText(''.join(map(str, self._contents))) @string.setter def string(self, s): if not isinstance(s, str): raise TypeError( '.string value "%s" must be a string or TexText. To set ' 'non-string content, use .contents' % s) self.contents = [TexText(s)] ################## # PUBLIC METHODS # ################## def append(self, *exprs): """Add contents to the expression. :param Union[TexExpr,str] exprs: List of contents to add >>> expr = TexExpr('textbf', ('hello',)) >>> expr TexExpr('textbf', ['hello']) >>> expr.append('world') >>> expr TexExpr('textbf', ['hello', 'world']) """ self._assert_supports_contents() self._contents.extend(exprs) def insert(self, i, *exprs): """Insert content at specified position into expression. :param int i: Position to add content to :param Union[TexExpr,str] exprs: List of contents to add >>> expr = TexExpr('textbf', ('hello',)) >>> expr TexExpr('textbf', ['hello']) >>> expr.insert(0, 'world') >>> expr TexExpr('textbf', ['world', 'hello']) >>> expr.insert(0, TexText('asdf')) >>> expr TexExpr('textbf', ['asdf', 'world', 'hello']) """ self._assert_supports_contents() for j, expr in enumerate(exprs): if isinstance(expr, TexExpr): expr.parent = self self._contents.insert(i + j, expr) def remove(self, expr): """Remove a provided expression from its list of contents. :param Union[TexExpr,str] expr: Content to add :return: index of the expression removed :rtype: int >>> expr = TexExpr('textbf', ('hello',)) >>> expr.remove('hello') 0 >>> expr TexExpr('textbf', []) """ self._assert_supports_contents() index = self._contents.index(expr) self._contents.remove(expr) return index def _supports_contents(self): return True def _assert_supports_contents(self): pass class TexEnv(TexExpr): r"""Abstraction for a LaTeX command, with starting and ending markers. Contains three attributes: 1. a human-readable environment name, 2. the environment delimiters 3. the environment's contents. >>> t = TexEnv('displaymath', r'\[', r'\]', ... ['\\mathcal{M} \\circ \\mathcal{A}']) >>> t TexEnv('displaymath', ['\\mathcal{M} \\circ \\mathcal{A}'], []) >>> print(t) \[\mathcal{M} \circ \mathcal{A}\] >>> len(list(t.children)) 0 """ _begin = None _end = None def __init__(self, name, begin, end, contents=(), args=(), preserve_whitespace=False, position=-1): r"""Initialization for Tex environment. :param str name: name of environment :param str begin: string denoting start of environment :param str end: string denoting end of environment :param iterable contents: list of contents :param iterable args: list of Tex Arguments :param bool preserve_whitespace: If false, elements containing only whitespace will be removed from contents. :param int position: position of first character in original source >>> env = TexEnv('math', '$', '$', [r'\$']) >>> str(env) '$\\$$' >>> env.begin = '^^' >>> env.end = '**' >>> str(env) '^^\\$**' """ super().__init__(name, contents, args, preserve_whitespace, position) self._begin = begin self._end = end @property def begin(self): return self._begin @begin.setter def begin(self, begin): self._begin = begin @property def end(self): return self._end @end.setter def end(self, end): self._end = end def __match__(self, name=None, attrs=()): """Check if given attributes match environment.""" if name in (self.name, self.begin + str(self.args), self.begin, self.end): return True return super().__match__(name, attrs) def __str__(self): contents = ''.join(map(str, self._contents)) if self.name == '[tex]': return contents else: return '%s%s%s' % ( self.begin + str(self.args), contents, self.end) def __repr__(self): if self.name == '[tex]': return str(self._contents) if not self.args and not self._contents: return "%s('%s')" % (self.__class__.__name__, self.name) return "%s('%s', %s, %s)" % ( self.__class__.__name__, self.name, repr(self._contents), repr(self.args)) class TexNamedEnv(TexEnv): r"""Abstraction for a LaTeX command, denoted by ``\begin{env}`` and ``\end{env}``. Contains three attributes: 1. the environment name itself, 2. the environment arguments, whether optional or required, and 3. the environment's contents. **Warning**: Note that *setting* TexNamedEnv.begin or TexNamedEnv.end has no effect. The begin and end tokens are always constructed from TexNamedEnv.name. >>> t = TexNamedEnv('tabular', ['\n0 & 0 & * \\\\\n1 & 1 & * \\\\\n'], ... [BraceGroup('c | c c')]) >>> t TexNamedEnv('tabular', ['\n0 & 0 & * \\\\\n1 & 1 & * \\\\\n'], [BraceGroup('c | c c')]) >>> print(t) \begin{tabular}{c | c c} 0 & 0 & * \\ 1 & 1 & * \\ \end{tabular} >>> len(list(t.children)) 0 >>> t = TexNamedEnv('equation', [r'5\sum_{i=0}^n i^2']) >>> str(t) '\\begin{equation}5\\sum_{i=0}^n i^2\\end{equation}' >>> t.name = 'eqn' >>> str(t) '\\begin{eqn}5\\sum_{i=0}^n i^2\\end{eqn}' """ def __init__(self, name, contents=(), args=(), preserve_whitespace=False, position=-1): """Initialization for Tex environment. :param str name: name of environment :param iterable contents: list of contents :param iterable args: list of Tex Arguments :param bool preserve_whitespace: If false, elements containing only whitespace will be removed from contents. :param int position: position of first character in original source """ super().__init__(name, r"\begin{%s}" % name, r"\end{%s}" % name, contents, args, preserve_whitespace, position=position) @property def begin(self): return r"\begin{%s}" % self.name @property def end(self): return r"\end{%s}" % self.name class TexUnNamedEnv(TexEnv): name = None begin = None end = None def __init__(self, contents=(), args=(), preserve_whitespace=False, position=-1): """Initialization for Tex environment. :param iterable contents: list of contents :param iterable args: list of Tex Arguments :param bool preserve_whitespace: If false, elements containing only whitespace will be removed from contents. :param int position: position of first character in original source """ assert self.name, 'Name must be non-falsey' assert self.begin and self.end, 'Delimiters must be non-falsey' super().__init__(self.name, self.begin, self.end, contents, args, preserve_whitespace, position=position) class TexDisplayMathModeEnv(TexUnNamedEnv): name = '$$' begin = '$$' end = '$$' token_begin = TC.DisplayMathSwitch token_end = TC.DisplayMathSwitch class TexMathModeEnv(TexUnNamedEnv): name = '$' begin = '$' end = '$' token_begin = TC.MathSwitch token_end = TC.MathSwitch class TexDisplayMathEnv(TexUnNamedEnv): name = 'displaymath' begin = r'\[' end = r'\]' token_begin = TC.DisplayMathGroupBegin token_end = TC.DisplayMathGroupEnd class TexMathEnv(TexUnNamedEnv): name = 'math' begin = r'\(' end = r'\)' token_begin = TC.MathGroupBegin token_end = TC.MathGroupEnd class TexCmd(TexExpr): r"""Abstraction for a LaTeX command. Contains two attributes: 1. the command name itself and 2. the command arguments, whether optional or required. >>> textit = TexCmd('textit', args=[BraceGroup('slant')]) >>> t = TexCmd('textbf', args=[BraceGroup('big ', textit, '.')]) >>> t TexCmd('textbf', [BraceGroup('big ', TexCmd('textit', [BraceGroup('slant')]), '.')]) >>> print(t) \textbf{big \textit{slant}.} >>> children = list(map(str, t.children)) >>> len(children) 1 >>> print(children[0]) \textit{slant} """ def __str__(self): if self._contents: return '\\%s%s%s' % (self.name, self.args, ''.join( [str(e) for e in self._contents])) return '\\%s%s' % (self.name, self.args) def __repr__(self): if not self.args: return "TexCmd('%s')" % self.name return "TexCmd('%s', %s)" % (self.name, repr(self.args)) def _supports_contents(self): return self.name == 'item' def _assert_supports_contents(self): if not self._supports_contents(): raise TypeError( 'Command "{}" has no children. `add_contents` is only valid' 'for: 1. environments like `itemize` and 2. `\\item`. ' 'Alternatively, you can add, edit, or delete arguments by ' 'modifying `.args`, which behaves like a list.' .format(self.name)) class TexText(TexExpr, str): r"""Abstraction for LaTeX text. Representing regular text objects in the parsed tree allows users to search and modify text objects as any other expression allows. >>> obj = TexNode(TexText('asdf gg')) >>> 'asdf' in obj True >>> 'err' in obj False >>> TexText('df ').strip() 'df' """ _has_custom_contain = True def __init__(self, text, position=-1): """Initialize text as tex expresssion. :param str text: Text content :param int position: position of first character in original source """ super().__init__('text', [text], position=position) self._text = text def __contains__(self, other): """ >>> obj = TexText(Token('asdf')) >>> 'a' in obj True >>> 'b' in obj False """ return other in self._text def __eq__(self, other): """ >>> TexText('asdf') == 'asdf' True >>> TexText('asdf') == TexText('asdf') True >>> TexText('asfd') == 'sdddsss' False """ if isinstance(other, TexText): return self._text == other._text if isinstance(other, str): return self._text == other return False def __str__(self): """ >>> TexText('asdf') 'asdf' """ return str(self._text) def __repr__(self): """ >>> TexText('asdf') 'asdf' """ return repr(self._text) ############# # Arguments # ############# class TexGroup(TexUnNamedEnv): """Abstraction for a LaTeX environment with single-character delimiters. Used primarily to identify and associate arguments with commands. """ def __init__(self, *contents, preserve_whitespace=False, position=-1): """Initialize argument using list of expressions. :param Union[str,TexCmd,TexEnv] exprs: Tex expressions contained in the argument. Can be other commands or environments, or even strings. :param int position: position of first character in original source """ super().__init__(contents, preserve_whitespace=preserve_whitespace, position=position) def __repr__(self): return '%s(%s)' % (self.__class__.__name__, ', '.join(map(repr, self._contents))) @classmethod def parse(cls, s): """Parse a string or list and return an Argument object. Naive implementation, does not parse expressions in provided string. :param Union[str,iterable] s: Either a string or a list, where the first and last elements are valid argument delimiters. >>> TexGroup.parse('[arg0]') BracketGroup('arg0') """ assert isinstance(s, str) for arg in arg_type: if s.startswith(arg.begin) and s.endswith(arg.end): return arg(s[len(arg.begin):-len(arg.end)]) raise TypeError('Malformed argument: %s. Must be an TexGroup or a string in' ' either brackets or curly braces.' % s) class BracketGroup(TexGroup): """Optional argument, denoted as ``[arg]``""" begin = '[' end = ']' name = 'BracketGroup' token_begin = TC.BracketBegin token_end = TC.BracketEnd class BraceGroup(TexGroup): """Required argument, denoted as ``{arg}``.""" begin = '{' end = '}' name = 'BraceGroup' token_begin = TC.GroupBegin token_end = TC.GroupEnd arg_type = (BracketGroup, BraceGroup) class TexArgs(list): r"""List of arguments for a TeX expression. Supports all standard list ops. Additional support for conversion from and to unparsed argument strings. >>> arguments = TexArgs(['\n', BraceGroup('arg0'), '[arg1]', '{arg2}']) >>> arguments [BraceGroup('arg0'), BracketGroup('arg1'), BraceGroup('arg2')] >>> arguments.all ['\n', BraceGroup('arg0'), BracketGroup('arg1'), BraceGroup('arg2')] >>> arguments[2] BraceGroup('arg2') >>> len(arguments) 3 >>> arguments[:2] [BraceGroup('arg0'), BracketGroup('arg1')] >>> isinstance(arguments[:2], TexArgs) True """ def __init__(self, args=[]): """List of arguments for a command. :param list args: List of parsed or unparsed arguments """ super().__init__() self.all = [] self.extend(args) def __coerce(self, arg): if isinstance(arg, str) and not arg.isspace(): arg = TexGroup.parse(arg) return arg def append(self, arg): """Append whitespace, an unparsed argument string, or an argument object. :param TexGroup arg: argument to add to the end of the list >>> arguments = TexArgs([BraceGroup('arg0'), '[arg1]', '{arg2}']) >>> arguments.append('[arg3]') >>> arguments[3] BracketGroup('arg3') >>> arguments.append(BraceGroup('arg4')) >>> arguments[4] BraceGroup('arg4') >>> len(arguments) 5 >>> arguments.append('\\n') >>> len(arguments) 5 >>> len(arguments.all) 6 """ self.insert(len(self), arg) def extend(self, args): """Extend mixture of unparsed argument strings, arguments objects, and whitespace. :param List[TexGroup] args: Arguments to add to end of the list >>> arguments = TexArgs([BraceGroup('arg0'), '[arg1]', '{arg2}']) >>> arguments.extend(['[arg3]', BraceGroup('arg4'), '\\t']) >>> len(arguments) 5 >>> arguments[4] BraceGroup('arg4') """ for arg in args: self.append(arg) def insert(self, i, arg): r"""Insert whitespace, an unparsed argument string, or an argument object. :param int i: Index to insert argument into :param TexGroup arg: Argument to insert >>> arguments = TexArgs(['\n', BraceGroup('arg0'), '[arg2]']) >>> arguments.insert(1, '[arg1]') >>> len(arguments) 3 >>> arguments [BraceGroup('arg0'), BracketGroup('arg1'), BracketGroup('arg2')] >>> arguments.all ['\n', BraceGroup('arg0'), BracketGroup('arg1'), BracketGroup('arg2')] >>> arguments.insert(10, '[arg3]') >>> arguments[3] BracketGroup('arg3') """ arg = self.__coerce(arg) if isinstance(arg, TexGroup): super().insert(i, arg) if len(self) <= 1: self.all.append(arg) else: if i > len(self): i = len(self) - 1 before = self[i - 1] index_before = self.all.index(before) self.all.insert(index_before + 1, arg) def remove(self, item): """Remove either an unparsed argument string or an argument object. :param Union[str,TexGroup] item: Item to remove >>> arguments = TexArgs([BraceGroup('arg0'), '[arg2]', '{arg3}']) >>> arguments.remove('{arg0}') >>> len(arguments) 2 >>> arguments[0] BracketGroup('arg2') >>> arguments.remove(arguments[0]) >>> arguments[0] BraceGroup('arg3') >>> arguments.remove(BraceGroup('arg3')) >>> len(arguments) 0 >>> arguments = TexArgs([ ... BraceGroup(TexCmd('color')), ... BraceGroup(TexCmd('color', [BraceGroup('blue')])) ... ]) >>> arguments.remove(arguments[0]) >>> len(arguments) 1 >>> arguments.remove(arguments[0]) >>> len(arguments) 0 """ item = self.__coerce(item) self.all.remove(item) super().remove(item) def pop(self, i): """Pop argument object at provided index. :param int i: Index to pop from the list >>> arguments = TexArgs([BraceGroup('arg0'), '[arg2]', '{arg3}']) >>> arguments.pop(1) BracketGroup('arg2') >>> len(arguments) 2 >>> arguments[0] BraceGroup('arg0') """ item = super().pop(i) j = self.all.index(item) return self.all.pop(j) def reverse(self): r"""Reverse both the list and the proxy `.all`. >>> args = TexArgs(['\n', BraceGroup('arg1'), BracketGroup('arg2')]) >>> args.reverse() >>> args.all [BracketGroup('arg2'), BraceGroup('arg1'), '\n'] >>> args [BracketGroup('arg2'), BraceGroup('arg1')] """ super().reverse() self.all.reverse() def clear(self): r"""Clear both the list and the proxy `.all`. >>> args = TexArgs(['\n', BraceGroup('arg1'), BracketGroup('arg2')]) >>> args.clear() >>> len(args) == len(args.all) == 0 True """ super().clear() self.all.clear() def __getitem__(self, key): """Standard list slicing. Returns TexArgs object for subset of list and returns an TexGroup object for single items. >>> arguments = TexArgs([BraceGroup('arg0'), '[arg1]', '{arg2}']) >>> arguments[2] BraceGroup('arg2') >>> arguments[:2] [BraceGroup('arg0'), BracketGroup('arg1')] """ value = super().__getitem__(key) if isinstance(value, list): return TexArgs(value) return value def __contains__(self, item): """Checks for membership. Allows string comparisons to args. >>> arguments = TexArgs(['{arg0}', '[arg1]']) >>> 'arg0' in arguments True >>> BracketGroup('arg0') in arguments False >>> BraceGroup('arg0') in arguments True >>> 'arg3' in arguments False """ if isinstance(item, str): return any([item == arg.string for arg in self]) return super().__contains__(item) def __str__(self): """Stringifies a list of arguments. >>> str(TexArgs(['{a}', '[b]', '{c}'])) '{a}[b]{c}' """ return ''.join(map(str, self)) def __repr__(self): """Makes list of arguments command-line friendly. >>> TexArgs(['{a}', '[b]', '{c}']) [BraceGroup('a'), BracketGroup('b'), BraceGroup('c')] """ return '[%s]' % ', '.join(map(repr, self))
30.274914
91
0.545358
import itertools import re from TexSoup.utils import CharToLineOffset, Token, TC, to_list __all__ = ['TexNode', 'TexCmd', 'TexEnv', 'TexGroup', 'BracketGroup', 'BraceGroup', 'TexArgs', 'TexText', 'TexMathEnv', 'TexDisplayMathEnv', 'TexNamedEnv', 'TexMathModeEnv', 'TexDisplayMathModeEnv'] e a valid TexExpr' super().__init__() self.expr = expr self.parent = None if src is not None: self.char_to_line = CharToLineOffset(src) else: self.char_to_line = None em__(self, item): return list(self.contents)[item] def __iter__(self): return iter(self.contents) def __match__(self, name=None, attrs=()): return self.expr.__match__(name, attrs) def __repr__(self): return str(self) def __str__(self): return str(self.expr) node.parent = self yield node @property def args(self): return self.expr.args @args.setter def args(self, args): assert isinstance(args, TexArgs), "`args` must be of type `TexArgs`" self.expr.args = args @property @to_list def children(self): for child in self.expr.children: node = TexNode(child) node.parent = self yield node @property @to_list def contents(self): for child in self.expr.contents: if isinstance(child, TexExpr): node = TexNode(child) node.parent = self yield node else: yield child @contents.setter def contents(self, contents): self.expr.contents = contents @property def descendants(self): return self.__descendants() @property def name(self): return self.expr.name @name.setter def name(self, name): self.expr.name = name @property def string(self): if isinstance(self.expr, TexCmd): assert len(self.expr.args) == 1, \ '.string is only valid for commands with one argument' return self.expr.args[0].string contents = list(self.contents) if isinstance(self.expr, TexEnv): assert len(contents) == 1 and \ isinstance(contents[0], (TexText, str)), \ '.string is only valid for environments with only text content' return contents[0] @string.setter def string(self, string): if isinstance(self.expr, TexCmd): assert len(self.expr.args) == 1, \ '.string is only valid for commands with one argument' self.expr.args[0].string = string contents = list(self.contents) if isinstance(self.expr, TexEnv): assert len(contents) == 1 and \ isinstance(contents[0], (TexText, str)), \ '.string is only valid for environments with only text content' self.contents = [string] @property def position(self): return self.expr.position @property @to_list def text(self): for descendant in self.contents: if isinstance(descendant, (TexText, Token)): yield descendant elif hasattr(descendant, 'text'): yield from descendant.text rmat(i)) for node in nodes: if not isinstance(node, TexNode): continue assert not node.parent, ( 'Inserted node should not already have parent. Call `.copy()` ' 'on node to fix.' ) node.parent = self self.expr.insert(i, *nodes) def char_pos_to_line(self, char_pos): assert self.char_to_line is not None, ( 'CharToLineOffset is not initialized. Pass src to TexNode ' 'constructor') return self.char_to_line(char_pos) def copy(self): return TexNode(self.expr) def count(self, name=None, **attrs): return len(list(self.find_all(name, **attrs))) def delete(self): parent = self.parent if parent.expr._supports_contents(): parent.remove(self) return for arg in parent.args: if self.expr in arg.contents: arg._contents.remove(self.expr) def find(self, name=None, **attrs): try: return self.find_all(name, **attrs)[0] except IndexError: return None @to_list def find_all(self, name=None, **attrs): for descendant in self.__descendants(): if hasattr(descendant, '__match__') and \ descendant.__match__(name, attrs): yield descendant def remove(self, node): self.expr.remove(node.expr) def replace_with(self, *nodes): self.parent.replace(self, *nodes) def replace(self, child, *nodes): self.expr.insert( self.expr.remove(child.expr), *nodes) def search_regex(self, pattern): for node in self.text: for match in re.finditer(pattern, node): body = match.group() start = match.start() yield Token(body, node.position + start) def __descendants(self): return itertools.chain(self.contents, *[c.descendants for c in self.children]) self.parent = None self._contents = list(contents) or [] self.preserve_whitespace = preserve_whitespace self.position = position for content in contents: if isinstance(content, (TexEnv, TexCmd)): content.parent = self tattr(self, 'name') if node_name not in name: return False else: attrs['name'] = name for k, v in attrs.items(): if getattr(self, k) != v: return False return True def __repr__(self): if not self.args: return "TexExpr('%s', %s)" % (self.name, repr(self._contents)) return "TexExpr('%s', %s, %s)" % ( self.name, repr(self._contents), repr(self.args)) ontents: yield content @property @to_list def children(self): return filter(lambda x: isinstance(x, (TexEnv, TexCmd)), self.contents) @property @to_list def contents(self): for content in self.all: if isinstance(content, TexText): content = content._text is_whitespace = isinstance(content, str) and content.isspace() if not is_whitespace or self.preserve_whitespace: yield content @contents.setter def contents(self, contents): if not isinstance(contents, (list, tuple)) or not all( isinstance(content, (str, TexExpr)) for content in contents): raise TypeError( '.contents value "%s" must be a list or tuple of strings or ' 'TexExprs' % contents) _contents = [TexText(c) if isinstance(c, str) else c for c in contents] self._contents = _contents @property def string(self): return TexText(''.join(map(str, self._contents))) @string.setter def string(self, s): if not isinstance(s, str): raise TypeError( '.string value "%s" must be a string or TexText. To set ' 'non-string content, use .contents' % s) self.contents = [TexText(s)] self self._contents.insert(i + j, expr) def remove(self, expr): self._assert_supports_contents() index = self._contents.index(expr) self._contents.remove(expr) return index def _supports_contents(self): return True def _assert_supports_contents(self): pass class TexEnv(TexExpr): _begin = None _end = None def __init__(self, name, begin, end, contents=(), args=(), preserve_whitespace=False, position=-1): super().__init__(name, contents, args, preserve_whitespace, position) self._begin = begin self._end = end @property def begin(self): return self._begin @begin.setter def begin(self, begin): self._begin = begin @property def end(self): return self._end @end.setter def end(self, end): self._end = end def __match__(self, name=None, attrs=()): if name in (self.name, self.begin + str(self.args), self.begin, self.end): return True return super().__match__(name, attrs) def __str__(self): contents = ''.join(map(str, self._contents)) if self.name == '[tex]': return contents else: return '%s%s%s' % ( self.begin + str(self.args), contents, self.end) def __repr__(self): if self.name == '[tex]': return str(self._contents) if not self.args and not self._contents: return "%s('%s')" % (self.__class__.__name__, self.name) return "%s('%s', %s, %s)" % ( self.__class__.__name__, self.name, repr(self._contents), repr(self.args)) class TexNamedEnv(TexEnv): def __init__(self, name, contents=(), args=(), preserve_whitespace=False, position=-1): super().__init__(name, r"\begin{%s}" % name, r"\end{%s}" % name, contents, args, preserve_whitespace, position=position) @property def begin(self): return r"\begin{%s}" % self.name @property def end(self): return r"\end{%s}" % self.name class TexUnNamedEnv(TexEnv): name = None begin = None end = None def __init__(self, contents=(), args=(), preserve_whitespace=False, position=-1): assert self.name, 'Name must be non-falsey' assert self.begin and self.end, 'Delimiters must be non-falsey' super().__init__(self.name, self.begin, self.end, contents, args, preserve_whitespace, position=position) class TexDisplayMathModeEnv(TexUnNamedEnv): name = '$$' begin = '$$' end = '$$' token_begin = TC.DisplayMathSwitch token_end = TC.DisplayMathSwitch class TexMathModeEnv(TexUnNamedEnv): name = '$' begin = '$' end = '$' token_begin = TC.MathSwitch token_end = TC.MathSwitch class TexDisplayMathEnv(TexUnNamedEnv): name = 'displaymath' begin = r'\[' end = r'\]' token_begin = TC.DisplayMathGroupBegin token_end = TC.DisplayMathGroupEnd class TexMathEnv(TexUnNamedEnv): name = 'math' begin = r'\(' end = r'\)' token_begin = TC.MathGroupBegin token_end = TC.MathGroupEnd class TexCmd(TexExpr): def __str__(self): if self._contents: return '\\%s%s%s' % (self.name, self.args, ''.join( [str(e) for e in self._contents])) return '\\%s%s' % (self.name, self.args) def __repr__(self): if not self.args: return "TexCmd('%s')" % self.name return "TexCmd('%s', %s)" % (self.name, repr(self.args)) def _supports_contents(self): return self.name == 'item' def _assert_supports_contents(self): if not self._supports_contents(): raise TypeError( 'Command "{}" has no children. `add_contents` is only valid' 'for: 1. environments like `itemize` and 2. `\\item`. ' 'Alternatively, you can add, edit, or delete arguments by ' 'modifying `.args`, which behaves like a list.' .format(self.name)) class TexText(TexExpr, str): _has_custom_contain = True def __init__(self, text, position=-1): super().__init__('text', [text], position=position) self._text = text def __contains__(self, other): return other in self._text def __eq__(self, other): if isinstance(other, TexText): return self._text == other._text if isinstance(other, str): return self._text == other return False def __str__(self): return str(self._text) def __repr__(self): return repr(self._text) hitespace=preserve_whitespace, position=position) def __repr__(self): return '%s(%s)' % (self.__class__.__name__, ', '.join(map(repr, self._contents))) @classmethod def parse(cls, s): assert isinstance(s, str) for arg in arg_type: if s.startswith(arg.begin) and s.endswith(arg.end): return arg(s[len(arg.begin):-len(arg.end)]) raise TypeError('Malformed argument: %s. Must be an TexGroup or a string in' ' either brackets or curly braces.' % s) class BracketGroup(TexGroup): begin = '[' end = ']' name = 'BracketGroup' token_begin = TC.BracketBegin token_end = TC.BracketEnd class BraceGroup(TexGroup): begin = '{' end = '}' name = 'BraceGroup' token_begin = TC.GroupBegin token_end = TC.GroupEnd arg_type = (BracketGroup, BraceGroup) class TexArgs(list): def __init__(self, args=[]): super().__init__() self.all = [] self.extend(args) def __coerce(self, arg): if isinstance(arg, str) and not arg.isspace(): arg = TexGroup.parse(arg) return arg def append(self, arg): self.insert(len(self), arg) def extend(self, args): for arg in args: self.append(arg) def insert(self, i, arg): arg = self.__coerce(arg) if isinstance(arg, TexGroup): super().insert(i, arg) if len(self) <= 1: self.all.append(arg) else: if i > len(self): i = len(self) - 1 before = self[i - 1] index_before = self.all.index(before) self.all.insert(index_before + 1, arg) def remove(self, item): item = self.__coerce(item) self.all.remove(item) super().remove(item) def pop(self, i): item = super().pop(i) j = self.all.index(item) return self.all.pop(j) def reverse(self): super().reverse() self.all.reverse() def clear(self): super().clear() self.all.clear() def __getitem__(self, key): value = super().__getitem__(key) if isinstance(value, list): return TexArgs(value) return value def __contains__(self, item): if isinstance(item, str): return any([item == arg.string for arg in self]) return super().__contains__(item) def __str__(self): return ''.join(map(str, self)) def __repr__(self): return '[%s]' % ', '.join(map(repr, self))
true
true
f7279d2a0928d92d1790424e41fa2a880cbb1be9
138
py
Python
multiples_list.py
GYosifov88/Python-Fundamentals
b46ba2822bd2dac6ff46830c6a520e559b448442
[ "MIT" ]
null
null
null
multiples_list.py
GYosifov88/Python-Fundamentals
b46ba2822bd2dac6ff46830c6a520e559b448442
[ "MIT" ]
null
null
null
multiples_list.py
GYosifov88/Python-Fundamentals
b46ba2822bd2dac6ff46830c6a520e559b448442
[ "MIT" ]
null
null
null
factor = int(input()) count = int(input()) new_list = [] for num in range (1, count+1): new_list.append(factor * num) print(new_list)
19.714286
33
0.65942
factor = int(input()) count = int(input()) new_list = [] for num in range (1, count+1): new_list.append(factor * num) print(new_list)
true
true
f7279d86e14fb0fc3c957ab9728d907bc9972e34
712
py
Python
sdk/test/test_user_location.py
aqualinkorg/aqualink-sdk
dad972d1dd5b74e8216bdc30521a8b76f7844733
[ "MIT" ]
1
2022-02-06T23:05:37.000Z
2022-02-06T23:05:37.000Z
sdk/test/test_user_location.py
aqualinkorg/aqualink-sdk
dad972d1dd5b74e8216bdc30521a8b76f7844733
[ "MIT" ]
3
2022-02-07T06:13:31.000Z
2022-03-11T12:43:39.000Z
sdk/test/test_user_location.py
aqualinkorg/aqualink-sdk
dad972d1dd5b74e8216bdc30521a8b76f7844733
[ "MIT" ]
null
null
null
""" Aqualink API documentation The Aqualink public API documentation # noqa: E501 The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech """ import sys import unittest import aqualink_sdk from aqualink_sdk.model.user_location import UserLocation class TestUserLocation(unittest.TestCase): """UserLocation unit test stubs""" def setUp(self): pass def tearDown(self): pass def testUserLocation(self): """Test UserLocation""" # FIXME: construct object with mandatory attributes with example values # model = UserLocation() # noqa: E501 pass if __name__ == '__main__': unittest.main()
19.777778
79
0.676966
import sys import unittest import aqualink_sdk from aqualink_sdk.model.user_location import UserLocation class TestUserLocation(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testUserLocation(self): s if __name__ == '__main__': unittest.main()
true
true
f7279df45c4b42335c35e8630786466cee4cd860
698
py
Python
models/final_model.py
Abxhor/Coldairarrow
3735beec8a6fa7ad9356375081229c68f0e83f3d
[ "MIT" ]
null
null
null
models/final_model.py
Abxhor/Coldairarrow
3735beec8a6fa7ad9356375081229c68f0e83f3d
[ "MIT" ]
null
null
null
models/final_model.py
Abxhor/Coldairarrow
3735beec8a6fa7ad9356375081229c68f0e83f3d
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """Stacking of some good solutions. IMPORTANT: To run this model you need run before the differents models. """ import pandas as pd import numpy as np df1 = pd.read_csv('submission40.csv') # 0.309812 (public leaderboard) df2 = pd.read_csv('submission41.csv') # 0.305985 (public leaderboard) df3 = pd.read_csv('submission42.csv') # 0.313587 (public leaderboard) df4 = pd.read_csv('submission45.csv') # 0.309749 (public leaderboard) df5 = pd.read_csv('submission47.csv') # 0.306439 (public leaderboard) df = pd.DataFrame() df['y'] = 0.2*df1['y'] + 0.23*df2['y'] + 0.2*df3['y'] + 0.15*df4['y'] + 0.22*df5['y'] df.to_csv('submission53.csv') # 0.301697 (public leaderboard)
33.238095
85
0.690544
import pandas as pd import numpy as np df1 = pd.read_csv('submission40.csv') df2 = pd.read_csv('submission41.csv') df3 = pd.read_csv('submission42.csv') df4 = pd.read_csv('submission45.csv') df5 = pd.read_csv('submission47.csv') df = pd.DataFrame() df['y'] = 0.2*df1['y'] + 0.23*df2['y'] + 0.2*df3['y'] + 0.15*df4['y'] + 0.22*df5['y'] df.to_csv('submission53.csv')
true
true
f7279e1c3124420e19cf7b1c5a2e96104f93c057
19,081
py
Python
777_all_in_one_v1.py
vlbthambawita/singan-polyp-aug-exp
b4ec5155f5c36a931fad022aec04dda6b3180b55
[ "MIT" ]
null
null
null
777_all_in_one_v1.py
vlbthambawita/singan-polyp-aug-exp
b4ec5155f5c36a931fad022aec04dda6b3180b55
[ "MIT" ]
null
null
null
777_all_in_one_v1.py
vlbthambawita/singan-polyp-aug-exp
b4ec5155f5c36a931fad022aec04dda6b3180b55
[ "MIT" ]
null
null
null
#========================================================= # Developer: Vajira Thambawita # Reference: https://github.com/meetshah1995/pytorch-semseg #========================================================= import argparse from datetime import datetime import os import copy from tqdm import tqdm import matplotlib.pyplot as plt import numpy as np #Pytorch import torch import torch.optim as optim from torch.optim import lr_scheduler import torch.nn as nn from torch.utils.data import DataLoader from torchvision import models, transforms,datasets, utils from torchvision.utils import save_image from torch.utils.tensorboard import SummaryWriter from torch.autograd import Variable from torchsummary import summary import segmentation_models_pytorch as smp from data.dataset import Dataset from data.prepare_data import prepare_data, prepare_test_data #from data import PolypsDatasetWithGridEncoding #from data import PolypsDatasetWithGridEncoding_TestData import pyra_pytorch as pyra from utils import dice_coeff, iou_pytorch, visualize import segmentation_models_pytorch as smp #====================================== # Get and set all input parameters #====================================== parser = argparse.ArgumentParser() # Hardware #parser.add_argument("--device", default="gpu", help="Device to run the code") parser.add_argument("--device_id", type=int, default=0, help="") # Optional parameters to identify the experiments parser.add_argument("--exp_name", type=str, help="A name to identify the experiment", required=True) #parser.add_argument("--py_file",default=os.path.abspath(__file__)) # store current python file # Directory and file handling parser.add_argument("--train_CSVs", nargs="+", default=None, help="CSV file list with image and mask paths") parser.add_argument("--val_CSVs", nargs="+", default=None, help="CSV file list with image and mask paths") parser.add_argument("--test_CSVs", nargs="+", default=None, help="CSV file list with image and mask paths") parser.add_argument("--out_dir", default="/work/vajira/DATA/sinGAN_polyps/sinGAN_exp_out/checkpoints", help="Main output dierectory") parser.add_argument("--tensorboard_dir", default="/work/vajira/DATA/sinGAN_polyps/sinGAN_exp_out/tensorboard", help="Folder to save output of tensorboard") parser.add_argument("--test_out_dir", default= "/work/vajira/DATA/sinGAN_polyps/sinGAN_exp_out/test_samples", help="Output folder for testing data" ) parser.add_argument("--best_checkpoint_name", type=str, default="best_checkpoint.pth", help="A name to save bet checkpoint") parser.add_argument("--img_size", type=int, default=128, help="Image height and width to resize") # Action handling parser.add_argument("--num_epochs", type=int, default=1, help="Numbe of epochs to train") parser.add_argument("--start_epoch", type=int, default=0, help="start epoch of training") parser.add_argument("--num_test_samples", type=int, default=5, help="Number of samples to test.") # smp parameters parser.add_argument("--model", help="The model to perform segmentation", required=True) parser.add_argument("--encoder", type=str, default='se_resnext50_32x4d', help="smp encoders") parser.add_argument("--encoder_weights", type=str, default='imagenet', help="encoder weights") parser.add_argument("--classes", default=[0,255], help="classes per pixel") parser.add_argument("--activation", type=str, default='softmax2d', help="last activation layers activation") #PYRA parser.add_argument("--pyra", type=bool, default=False, help="To enable PYRA grid encoding.") parser.add_argument("--grid_sizes_train", type=list, default=[256], help="Grid sizes to use in training") parser.add_argument("--grid_sizes_val", type=list, default=[256], help="Grid sizes to use in training") parser.add_argument("--grid_sizes_test", type=list, default=[256], help="Grid sizes to use in testing") parser.add_argument("--in_channels", type=int, default=3, help="Number of input channgels") # Parameters parser.add_argument("--bs", type=int, default=8, help="Mini batch size") parser.add_argument("--val_bs", type=int, default=1, help="Batch size") parser.add_argument("--lr", type=float, default=0.0001, help="Learning rate for training") parser.add_argument("--lr_change_point", type=int, default=50, help="After this point LR will be changed.") parser.add_argument("--num_workers", type=int, default=12, help="Number of workers in dataloader") parser.add_argument("--weight_decay", type=float, default=1e-5, help="weight decay of the optimizer") parser.add_argument("--lr_sch_factor", type=float, default=0.1, help="Factor to reduce lr in the scheduler") parser.add_argument("--lr_sch_patience", type=int, default=25, help="Num of epochs to be patience for updating lr") parser.add_argument("--num_samples", type=int, default=5, help="Number of samples to print from validation set") parser.add_argument("action", type=str, help="Select an action to run", choices=["train", "retrain", "test", "check", "check_val"]) parser.add_argument("--checkpoint_interval", type=int, default=25, help="Interval to save checkpoint models") #parser.add_argument("--fold", type=str, default="fold_1", help="Select the validation fold", choices=["fold_1", "fold_2", "fold_3"]) #parser.add_argument("--num_test", default= 200, type=int, help="Number of samples to test set from 1k dataset") #parser.add_argument("--model_path", default="", help="Model path to load weights") #parser.add_argument("--num_of_samples", default=30, type=int, help="Number of samples to validate (Montecalo sampling)") parser.add_argument("--record_name", type=str, default="VAL", help="Some name to identify records in tensorboard output") opt = parser.parse_args() #========================================== # Device handling #========================================== torch.cuda.set_device(opt.device_id) DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") opt.device = DEVICE #=========================================== # Folder handling #=========================================== #make output folder if not exist os.makedirs(opt.out_dir, exist_ok=True) # make subfolder in the output folder #py_file_name = opt.py_file.split("/")[-1] # Get python file name (soruce code name) CHECKPOINT_DIR = os.path.join(opt.out_dir, opt.exp_name + "/checkpoints") os.makedirs(CHECKPOINT_DIR, exist_ok=True) # make tensorboard subdirectory for the experiment tensorboard_exp_dir = os.path.join(opt.tensorboard_dir, opt.exp_name) os.makedirs( tensorboard_exp_dir, exist_ok=True) #========================================== # Tensorboard #========================================== # Initialize summary writer writer = SummaryWriter(tensorboard_exp_dir) #========================================== # Prepare Data #========================================== #================================================ # Train the model #================================================ def train_model(train_loader, valid_loader, model, loss, metrics, optimizer, opt): # create epoch runners # it is a simple loop of iterating over dataloader`s samples train_epoch = smp.utils.train.TrainEpoch( model, loss=loss, metrics=metrics, optimizer=optimizer, device=DEVICE, verbose=True, ) valid_epoch = smp.utils.train.ValidEpoch( model, loss=loss, metrics=metrics, device=DEVICE, verbose=True, ) max_score = 0 best_chk_path = os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name) for i in range(opt.start_epoch + 1, opt.start_epoch + opt.num_epochs +1 ): print('\nEpoch: {}'.format(i)) train_logs = train_epoch.run(train_loader) valid_logs = valid_epoch.run(valid_loader) # do something (save model, change lr, etc.) if max_score < valid_logs['iou_score']: max_score = valid_logs['iou_score'] torch.save({"model":model, "epoch": i}, best_chk_path) print('Best Model saved!') print("Testing....") do_test(opt) print("Tested") if i == opt.lr_change_point: optimizer.param_groups[0]['lr'] = 1e-5 print('Decrease decoder learning rate to 1e-5!') # writing to logs to tensorboard for key, value in train_logs.items(): writer.add_scalar(f"Train/{key}", value, i) for key, value in valid_logs.items(): writer.add_scalar(f"Valid/{key}", value, i) # update here #============================================== # Heatmap generator from tensor #============================================== def generate_heatmapts(img_tensor): print(img_tensor.shape) fig_list = [] for n in range(img_tensor.shape[0]): img = img_tensor[n] img = img.squeeze(dim=0) img_np = img.detach().cpu().numpy() #img_np = np.transforms(img_np, (1,2,0)) plt.imshow(img_np, cmap="hot") fig = plt.gcf() fig_list.append(fig) # plt.clf() plt.close() return fig_list #=============================================== # Prepare models #=============================================== def prepare_model(opt): # model = UNet(n_channels=4, n_classes=1) # 4 = 3 channels + 1 grid encode # create segmentation model with pretrained encoder model = getattr(smp, opt.model)( encoder_name=opt.encoder, in_channels=opt.in_channels, encoder_weights=opt.encoder_weights, classes=len(opt.classes), activation=opt.activation, ) return model #==================================== # Run training process #==================================== def run_train(opt): model = prepare_model(opt) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) train_loader, val_loader = prepare_data(opt, preprocessing_fn=None) loss = smp.utils.losses.DiceLoss(ignore_channels=[0]) metrics = [ smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[0]), ] optimizer = torch.optim.Adam([ dict(params=model.parameters(), lr=opt.lr), ]) train_model(train_loader, val_loader, model, loss, metrics, optimizer, opt) #==================================== # Re-train process #==================================== def run_retrain(opt): checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name)) opt.start_epoch = checkpoint_dict["epoch"] model = checkpoint_dict["model"] print("Model epoch:", checkpoint_dict["epoch"]) print("Model retrain started from epoch:", opt.start_epoch) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) train_loader, val_loader = prepare_data(opt, preprocessing_fn) loss = smp.utils.losses.DiceLoss() metrics = [ smp.utils.metrics.IoU(threshold=0.5), ] optimizer = torch.optim.Adam([ dict(params=model.parameters(), lr=opt.lr), ]) train_model(train_loader, val_loader, model, loss, metrics, optimizer, opt) #===================================== # Check model #==================================== def check_model_graph(): raise NotImplementedError #=================================== # Inference from pre-trained models #=================================== def do_test(opt): checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name)) test_epoch = checkpoint_dict["epoch"] best_model = checkpoint_dict["model"] print("Model best epoch:", test_epoch) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) test_dataset = prepare_test_data(opt, preprocessing_fn=None) test_dataset_vis = prepare_test_data(opt, preprocessing_fn=None) for i in range(opt.num_test_samples): image, mask = test_dataset[i] image_vis, _ = test_dataset_vis[i] #print(image) mask_tensor = torch.from_numpy(mask).to(opt.device).unsqueeze(0) image_tensor = torch.from_numpy(image).to(opt.device).unsqueeze(0) pr_mask = best_model.predict(image_tensor) pr_mask = pr_mask.squeeze().cpu().numpy().round() fig = visualize( input_image_new=np.transpose(image_vis, (1,2,0)).astype(int), GT_mask_0=mask[0, :,:], Pred_mask_0 = pr_mask[0,:,:], GT_mask_1= mask[1,:,:], Pred_mask_1 = pr_mask[1, :,:] ) fig.savefig(f"./test_202_{i}.png") writer.add_figure(f"Test_sample/sample-{i}", fig, global_step=test_epoch) def check_test_score(opt): checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name)) test_best_epoch = checkpoint_dict["epoch"] best_model = checkpoint_dict["model"] print("Model best epoch:", test_best_epoch) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) test_dataset = prepare_test_data(opt, preprocessing_fn=None) test_dataloader = DataLoader(test_dataset, num_workers=48) loss = smp.utils.losses.DiceLoss() # Testing with two class layers metrics = [ #smp.utils.metrics.IoU(threshold=0.5), smp.utils.metrics.IoU(threshold=0.5, ignore_channels=None), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-test-score", str(logs), global_step=test_best_epoch) # Testing with only class layer 1 (polyps) loss = smp.utils.losses.DiceLoss(ignore_channels=[0]) metrics = [ #smp.utils.metrics.IoU(threshold=0.5), smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[0]), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-test-score-ignore-channel-0", str(logs), global_step=test_best_epoch) # Testing with only class layer 0 (BG) loss = smp.utils.losses.DiceLoss(ignore_channels=[1]) metrics = [ #smp.utils.metrics.IoU(threshold=0.5), smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[1]), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-test-score-ignore-channel-1", str(logs), global_step=test_best_epoch) def check_val_full_score(opt): # changing test data files into val data #opt.test_CSVs = opt.val_CSVs #opt.record_name = "VAL" checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name)) test_best_epoch = checkpoint_dict["epoch"] best_model = checkpoint_dict["model"] print("Model best epoch:", test_best_epoch) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) test_dataset = prepare_test_data(opt, preprocessing_fn=None) test_dataloader = DataLoader(test_dataset, num_workers=12) loss = smp.utils.losses.DiceLoss() # Testing with two class layers metrics = [ #smp.utils.metrics.IoU(threshold=0.5), smp.utils.metrics.IoU(threshold=0.5, ignore_channels=None), smp.utils.metrics.Fscore(threshold=0.5, ignore_channels=None), smp.utils.metrics.Accuracy(threshold=0.5, ignore_channels=None), smp.utils.metrics.Recall(threshold=0.5, ignore_channels=None), smp.utils.metrics.Precision(threshold=0.5, ignore_channels=None), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-scores-->{opt.record_name}", str(logs), global_step=test_best_epoch) # Testing with only class layer 1 (polyps) loss = smp.utils.losses.DiceLoss(ignore_channels=[0]) metrics = [ #smp.utils.metrics.IoU(threshold=0.5), smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[0]), smp.utils.metrics.Fscore(threshold=0.5, ignore_channels=[0]), smp.utils.metrics.Accuracy(threshold=0.5, ignore_channels=[0]), smp.utils.metrics.Recall(threshold=0.5, ignore_channels=[0]), smp.utils.metrics.Precision(threshold=0.5, ignore_channels=[0]), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-val-scores-ignore-channel-0-->{opt.record_name}", str(logs), global_step=test_best_epoch) # Testing with only class layer 0 (BG) loss = smp.utils.losses.DiceLoss(ignore_channels=[1]) metrics = [ #smp.utils.metrics.IoU(threshold=0.5), smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[1]), smp.utils.metrics.Fscore(threshold=0.5, ignore_channels=[1]), smp.utils.metrics.Accuracy(threshold=0.5, ignore_channels=[1]), smp.utils.metrics.Recall(threshold=0.5, ignore_channels=[1]), smp.utils.metrics.Precision(threshold=0.5, ignore_channels=[1]), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-val-scores-ignore-channel-1-->{opt.record_name}", str(logs), global_step=test_best_epoch) if __name__ == "__main__": #data_loaders = prepare_data() print(vars(opt)) print("Test OK") # Train or retrain or inference if opt.action == "train": print("Training process is strted..!") run_train(opt) pass elif opt.action == "retrain": print("Retrainning process is strted..!") run_retrain(opt) pass elif opt.action == "test": print("Inference process is strted..!") do_test(opt) print("Done") elif opt.action == "check": check_test_score(opt) print("Check pass") elif opt.action == "check_val": check_val_full_score(opt) # Finish tensorboard writer writer.close()
32.728988
133
0.639432
import argparse from datetime import datetime import os import copy from tqdm import tqdm import matplotlib.pyplot as plt import numpy as np import torch import torch.optim as optim from torch.optim import lr_scheduler import torch.nn as nn from torch.utils.data import DataLoader from torchvision import models, transforms,datasets, utils from torchvision.utils import save_image from torch.utils.tensorboard import SummaryWriter from torch.autograd import Variable from torchsummary import summary import segmentation_models_pytorch as smp from data.dataset import Dataset from data.prepare_data import prepare_data, prepare_test_data import pyra_pytorch as pyra from utils import dice_coeff, iou_pytorch, visualize import segmentation_models_pytorch as smp parser = argparse.ArgumentParser() parser.add_argument("--device_id", type=int, default=0, help="") parser.add_argument("--exp_name", type=str, help="A name to identify the experiment", required=True) train_CSVs", nargs="+", default=None, help="CSV file list with image and mask paths") parser.add_argument("--val_CSVs", nargs="+", default=None, help="CSV file list with image and mask paths") parser.add_argument("--test_CSVs", nargs="+", default=None, help="CSV file list with image and mask paths") parser.add_argument("--out_dir", default="/work/vajira/DATA/sinGAN_polyps/sinGAN_exp_out/checkpoints", help="Main output dierectory") parser.add_argument("--tensorboard_dir", default="/work/vajira/DATA/sinGAN_polyps/sinGAN_exp_out/tensorboard", help="Folder to save output of tensorboard") parser.add_argument("--test_out_dir", default= "/work/vajira/DATA/sinGAN_polyps/sinGAN_exp_out/test_samples", help="Output folder for testing data" ) parser.add_argument("--best_checkpoint_name", type=str, default="best_checkpoint.pth", help="A name to save bet checkpoint") parser.add_argument("--img_size", type=int, default=128, help="Image height and width to resize") parser.add_argument("--num_epochs", type=int, default=1, help="Numbe of epochs to train") parser.add_argument("--start_epoch", type=int, default=0, help="start epoch of training") parser.add_argument("--num_test_samples", type=int, default=5, help="Number of samples to test.") parser.add_argument("--model", help="The model to perform segmentation", required=True) parser.add_argument("--encoder", type=str, default='se_resnext50_32x4d', help="smp encoders") parser.add_argument("--encoder_weights", type=str, default='imagenet', help="encoder weights") parser.add_argument("--classes", default=[0,255], help="classes per pixel") parser.add_argument("--activation", type=str, default='softmax2d', help="last activation layers activation") parser.add_argument("--pyra", type=bool, default=False, help="To enable PYRA grid encoding.") parser.add_argument("--grid_sizes_train", type=list, default=[256], help="Grid sizes to use in training") parser.add_argument("--grid_sizes_val", type=list, default=[256], help="Grid sizes to use in training") parser.add_argument("--grid_sizes_test", type=list, default=[256], help="Grid sizes to use in testing") parser.add_argument("--in_channels", type=int, default=3, help="Number of input channgels") parser.add_argument("--bs", type=int, default=8, help="Mini batch size") parser.add_argument("--val_bs", type=int, default=1, help="Batch size") parser.add_argument("--lr", type=float, default=0.0001, help="Learning rate for training") parser.add_argument("--lr_change_point", type=int, default=50, help="After this point LR will be changed.") parser.add_argument("--num_workers", type=int, default=12, help="Number of workers in dataloader") parser.add_argument("--weight_decay", type=float, default=1e-5, help="weight decay of the optimizer") parser.add_argument("--lr_sch_factor", type=float, default=0.1, help="Factor to reduce lr in the scheduler") parser.add_argument("--lr_sch_patience", type=int, default=25, help="Num of epochs to be patience for updating lr") parser.add_argument("--num_samples", type=int, default=5, help="Number of samples to print from validation set") parser.add_argument("action", type=str, help="Select an action to run", choices=["train", "retrain", "test", "check", "check_val"]) parser.add_argument("--checkpoint_interval", type=int, default=25, help="Interval to save checkpoint models") parser.add_argument("--record_name", type=str, default="VAL", help="Some name to identify records in tensorboard output") opt = parser.parse_args() torch.cuda.set_device(opt.device_id) DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") opt.device = DEVICE os.makedirs(opt.out_dir, exist_ok=True) r, opt.exp_name + "/checkpoints") os.makedirs(CHECKPOINT_DIR, exist_ok=True) tensorboard_exp_dir = os.path.join(opt.tensorboard_dir, opt.exp_name) os.makedirs( tensorboard_exp_dir, exist_ok=True) writer = SummaryWriter(tensorboard_exp_dir) def train_model(train_loader, valid_loader, model, loss, metrics, optimizer, opt): train_epoch = smp.utils.train.TrainEpoch( model, loss=loss, metrics=metrics, optimizer=optimizer, device=DEVICE, verbose=True, ) valid_epoch = smp.utils.train.ValidEpoch( model, loss=loss, metrics=metrics, device=DEVICE, verbose=True, ) max_score = 0 best_chk_path = os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name) for i in range(opt.start_epoch + 1, opt.start_epoch + opt.num_epochs +1 ): print('\nEpoch: {}'.format(i)) train_logs = train_epoch.run(train_loader) valid_logs = valid_epoch.run(valid_loader) if max_score < valid_logs['iou_score']: max_score = valid_logs['iou_score'] torch.save({"model":model, "epoch": i}, best_chk_path) print('Best Model saved!') print("Testing....") do_test(opt) print("Tested") if i == opt.lr_change_point: optimizer.param_groups[0]['lr'] = 1e-5 print('Decrease decoder learning rate to 1e-5!') for key, value in train_logs.items(): writer.add_scalar(f"Train/{key}", value, i) for key, value in valid_logs.items(): writer.add_scalar(f"Valid/{key}", value, i) def generate_heatmapts(img_tensor): print(img_tensor.shape) fig_list = [] for n in range(img_tensor.shape[0]): img = img_tensor[n] img = img.squeeze(dim=0) img_np = img.detach().cpu().numpy() plt.imshow(img_np, cmap="hot") fig = plt.gcf() fig_list.append(fig) plt.close() return fig_list def prepare_model(opt): opt.model)( encoder_name=opt.encoder, in_channels=opt.in_channels, encoder_weights=opt.encoder_weights, classes=len(opt.classes), activation=opt.activation, ) return model def run_train(opt): model = prepare_model(opt) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) train_loader, val_loader = prepare_data(opt, preprocessing_fn=None) loss = smp.utils.losses.DiceLoss(ignore_channels=[0]) metrics = [ smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[0]), ] optimizer = torch.optim.Adam([ dict(params=model.parameters(), lr=opt.lr), ]) train_model(train_loader, val_loader, model, loss, metrics, optimizer, opt) def run_retrain(opt): checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name)) opt.start_epoch = checkpoint_dict["epoch"] model = checkpoint_dict["model"] print("Model epoch:", checkpoint_dict["epoch"]) print("Model retrain started from epoch:", opt.start_epoch) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) train_loader, val_loader = prepare_data(opt, preprocessing_fn) loss = smp.utils.losses.DiceLoss() metrics = [ smp.utils.metrics.IoU(threshold=0.5), ] optimizer = torch.optim.Adam([ dict(params=model.parameters(), lr=opt.lr), ]) train_model(train_loader, val_loader, model, loss, metrics, optimizer, opt) def check_model_graph(): raise NotImplementedError def do_test(opt): checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name)) test_epoch = checkpoint_dict["epoch"] best_model = checkpoint_dict["model"] print("Model best epoch:", test_epoch) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) test_dataset = prepare_test_data(opt, preprocessing_fn=None) test_dataset_vis = prepare_test_data(opt, preprocessing_fn=None) for i in range(opt.num_test_samples): image, mask = test_dataset[i] image_vis, _ = test_dataset_vis[i] mask_tensor = torch.from_numpy(mask).to(opt.device).unsqueeze(0) image_tensor = torch.from_numpy(image).to(opt.device).unsqueeze(0) pr_mask = best_model.predict(image_tensor) pr_mask = pr_mask.squeeze().cpu().numpy().round() fig = visualize( input_image_new=np.transpose(image_vis, (1,2,0)).astype(int), GT_mask_0=mask[0, :,:], Pred_mask_0 = pr_mask[0,:,:], GT_mask_1= mask[1,:,:], Pred_mask_1 = pr_mask[1, :,:] ) fig.savefig(f"./test_202_{i}.png") writer.add_figure(f"Test_sample/sample-{i}", fig, global_step=test_epoch) def check_test_score(opt): checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name)) test_best_epoch = checkpoint_dict["epoch"] best_model = checkpoint_dict["model"] print("Model best epoch:", test_best_epoch) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) test_dataset = prepare_test_data(opt, preprocessing_fn=None) test_dataloader = DataLoader(test_dataset, num_workers=48) loss = smp.utils.losses.DiceLoss() metrics = [ smp.utils.metrics.IoU(threshold=0.5, ignore_channels=None), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-test-score", str(logs), global_step=test_best_epoch) loss = smp.utils.losses.DiceLoss(ignore_channels=[0]) metrics = [ smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[0]), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-test-score-ignore-channel-0", str(logs), global_step=test_best_epoch) loss = smp.utils.losses.DiceLoss(ignore_channels=[1]) metrics = [ smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[1]), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-test-score-ignore-channel-1", str(logs), global_step=test_best_epoch) def check_val_full_score(opt): checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name)) test_best_epoch = checkpoint_dict["epoch"] best_model = checkpoint_dict["model"] print("Model best epoch:", test_best_epoch) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) test_dataset = prepare_test_data(opt, preprocessing_fn=None) test_dataloader = DataLoader(test_dataset, num_workers=12) loss = smp.utils.losses.DiceLoss() metrics = [ smp.utils.metrics.IoU(threshold=0.5, ignore_channels=None), smp.utils.metrics.Fscore(threshold=0.5, ignore_channels=None), smp.utils.metrics.Accuracy(threshold=0.5, ignore_channels=None), smp.utils.metrics.Recall(threshold=0.5, ignore_channels=None), smp.utils.metrics.Precision(threshold=0.5, ignore_channels=None), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-scores-->{opt.record_name}", str(logs), global_step=test_best_epoch) loss = smp.utils.losses.DiceLoss(ignore_channels=[0]) metrics = [ smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[0]), smp.utils.metrics.Fscore(threshold=0.5, ignore_channels=[0]), smp.utils.metrics.Accuracy(threshold=0.5, ignore_channels=[0]), smp.utils.metrics.Recall(threshold=0.5, ignore_channels=[0]), smp.utils.metrics.Precision(threshold=0.5, ignore_channels=[0]), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-val-scores-ignore-channel-0-->{opt.record_name}", str(logs), global_step=test_best_epoch) loss = smp.utils.losses.DiceLoss(ignore_channels=[1]) metrics = [ smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[1]), smp.utils.metrics.Fscore(threshold=0.5, ignore_channels=[1]), smp.utils.metrics.Accuracy(threshold=0.5, ignore_channels=[1]), smp.utils.metrics.Recall(threshold=0.5, ignore_channels=[1]), smp.utils.metrics.Precision(threshold=0.5, ignore_channels=[1]), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-val-scores-ignore-channel-1-->{opt.record_name}", str(logs), global_step=test_best_epoch) if __name__ == "__main__": print(vars(opt)) print("Test OK") if opt.action == "train": print("Training process is strted..!") run_train(opt) pass elif opt.action == "retrain": print("Retrainning process is strted..!") run_retrain(opt) pass elif opt.action == "test": print("Inference process is strted..!") do_test(opt) print("Done") elif opt.action == "check": check_test_score(opt) print("Check pass") elif opt.action == "check_val": check_val_full_score(opt) writer.close()
true
true
f7279ecc02853cb1115ebc5b8d75e8798d77b6ea
5,301
py
Python
tests/app/models/test_webauthn_credential.py
TechforgoodCAST/notifications-admin
0a9e06aafd79d0fbe50c26a85bf757aaeaa59340
[ "MIT" ]
null
null
null
tests/app/models/test_webauthn_credential.py
TechforgoodCAST/notifications-admin
0a9e06aafd79d0fbe50c26a85bf757aaeaa59340
[ "MIT" ]
1
2021-10-19T13:34:15.000Z
2021-10-19T13:34:15.000Z
tests/app/models/test_webauthn_credential.py
TechforgoodCAST/notifications-admin
0a9e06aafd79d0fbe50c26a85bf757aaeaa59340
[ "MIT" ]
1
2021-03-05T13:18:44.000Z
2021-03-05T13:18:44.000Z
import base64 import pytest from fido2 import cbor from fido2.cose import ES256 from app.models.webauthn_credential import RegistrationError, WebAuthnCredential # noqa adapted from https://github.com/duo-labs/py_webauthn/blob/90e3d97e0182899a35a70fc510280b4082cce19b/tests/test_webauthn.py#L14-L24 SESSION_STATE = {'challenge': 'bPzpX3hHQtsp9evyKYkaZtVc9UN07PUdJ22vZUdDp94', 'user_verification': 'discouraged'} CLIENT_DATA_JSON = b'{"type": "webauthn.create", "clientExtensions": {}, "challenge": "bPzpX3hHQtsp9evyKYkaZtVc9UN07PUdJ22vZUdDp94", "origin": "https://webauthn.io"}' # noqa # had to use the cbor2 library to re-encode the attestationObject due to implementation differences ATTESTATION_OBJECT = base64.b64decode(b'o2NmbXRoZmlkby11MmZnYXR0U3RtdKJjc2lnWEgwRgIhAI1qbvWibQos/t3zsTU05IXw1Ek3SDApATok09uc4UBwAiEAv0fB/lgb5Ot3zJ691Vje6iQLAtLhJDiA8zDxaGjcE3hjeDVjgVkCUzCCAk8wggE3oAMCAQICBDxoKU0wDQYJKoZIhvcNAQELBQAwLjEsMCoGA1UEAxMjWXViaWNvIFUyRiBSb290IENBIFNlcmlhbCA0NTcyMDA2MzEwIBcNMTQwODAxMDAwMDAwWhgPMjA1MDA5MDQwMDAwMDBaMDExLzAtBgNVBAMMJll1YmljbyBVMkYgRUUgU2VyaWFsIDIzOTI1NzM0ODExMTE3OTAxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEvd9nk9t3lMNQMXHtLE1FStlzZnUaSLql2fm1ajoggXlrTt8rzXuSehSTEPvEaEdv/FeSqX22L6Aoa8ajIAIOY6M7MDkwIgYJKwYBBAGCxAoCBBUxLjMuNi4xLjQuMS40MTQ4Mi4xLjUwEwYLKwYBBAGC5RwCAQEEBAMCBSAwDQYJKoZIhvcNAQELBQADggEBAKrADVEJfuwVpIazebzEg0D4Z9OXLs5qZ/ukcONgxkRZ8K04QtP/CB5x6olTlxsj+SXArQDCRzEYUgbws6kZKfuRt2a1P+EzUiqDWLjRILSr+3/o7yR7ZP/GpiFKwdm+czb94POoGD+TS1IYdfXj94mAr5cKWx4EKjh210uovu/pLdLjc8xkQciUrXzZpPR9rT2k/q9HkZhHU+NaCJzky+PTyDbq0KKnzqVhWtfkSBCGw3ezZkTS+5lrvOKbIa24lfeTgu7FST5OwTPCFn8HcfWZMXMSD/KNU+iBqJdAwTLPPDRoLLvPTl29weCAIh+HUpmBQd0UltcPOrA/LFvAf61oYXV0aERhdGFYwnSm6pITyZwvdLIkkrMgz0AmKpTBqVCgOX8pJQtghB7wQQAAAAAAAAAAAAAAAAAAAAAAAAAAAECKU1ppjl9gmhHWyDkgHsUvZmhr6oF3/lD3llzLE2SaOSgOGIsIuAQqgp8JQSUu3r/oOaP8RS44dlQjrH+ALfYtpAECAyYhWCAxnqAfESXOYjKUc2WACuXZ3ch0JHxV0VFrrTyjyjIHXCJYIFnx8H87L4bApR4M+hPcV+fHehEOeW+KCyd0H+WGY8s6') # noqa # manually adapted by working out which character in the encoded CBOR corresponds to the public key algorithm ID UNSUPPORTED_ATTESTATION_OBJECT = base64.b64decode(b'o2NmbXRoZmlkby11MmZnYXR0U3RtdKJjc2lnWEgwRgIhAI1qbvWibQos/t3zsTU05IXw1Ek3SDApATok09uc4UBwAiEAv0fB/lgb5Ot3zJ691Vje6iQLAtLhJDiA8zDxaGjcE3hjeDVjgVkCUzCCAk8wggE3oAMCAQICBDxoKU0wDQYJKoZIhvcNAQELBQAwLjEsMCoGA1UEAxMjWXViaWNvIFUyRiBSb290IENBIFNlcmlhbCA0NTcyMDA2MzEwIBcNMTQwODAxMDAwMDAwWhgPMjA1MDA5MDQwMDAwMDBaMDExLzAtBgNVBAMMJll1YmljbyBVMkYgRUUgU2VyaWFsIDIzOTI1NzM0ODExMTE3OTAxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEvd9nk9t3lMNQMXHtLE1FStlzZnUaSLql2fm1ajoggXlrTt8rzXuSehSTEPvEaEdv/FeSqX22L6Aoa8ajIAIOY6M7MDkwIgYJKwYBBAGCxAoCBBUxLjMuNi4xLjQuMS40MTQ4Mi4xLjUwEwYLKwYBBAGC5RwCAQEEBAMCBSAwDQYJKoZIhvcNAQELBQADggEBAKrADVEJfuwVpIazebzEg0D4Z9OXLs5qZ/ukcONgxkRZ8K04QtP/CB5x6olTlxsj+SXArQDCRzEYUgbws6kZKfuRt2a1P+EzUiqDWLjRILSr+3/o7yR7ZP/GpiFKwdm+czb94POoGD+TS1IYdfXj94mAr5cKWx4EKjh210uovu/pLdLjc8xkQciUrXzZpPR9rT2k/q9HkZhHU+NaCJzky+PTyDbq0KKnzqVhWtfkSBCGw3ezZkTS+5lrvOKbIa24lfeTgu7FST5OwTPCFn8HcfWZMXMSD/KNU+iBqJdAwTLPPDRoLLvPTl29weCAIh+HUpmBQd0UltcPOrA/LFvAf61oYXV0aERhdGFYwnSm6pITyZwvdLIkkrMgz0AmKpTBqVCgOX8pJQtghB7wQQAAAAAAAAAAAAAAAAAAAAAAAAAAAECKU1ppjl9gmhHWyDkgHsUvZmhr6oF3/lD3llzLE2SaOSgOGIsIuAQqgp8JQSUu3r/oOaP8RS44dlQjrH+ALfYtpAECAyUhWCAxnqAfESXOYjKUc2WACuXZ3ch0JHxV0VFrrTyjyjIHXCJYIFnx8H87L4bApR4M+hPcV+fHehEOeW+KCyd0H+WGY8s6') # noqa def test_from_registration_verifies_response(webauthn_dev_server): registration_response = { 'clientDataJSON': CLIENT_DATA_JSON, 'attestationObject': ATTESTATION_OBJECT, } credential = WebAuthnCredential.from_registration(SESSION_STATE, registration_response) assert credential.name == 'Unnamed key' assert credential.registration_response == base64.b64encode(cbor.encode(registration_response)).decode('utf-8') credential_data = credential.to_credential_data() assert type(credential_data.credential_id) is bytes assert type(credential_data.aaguid) is bytes assert credential_data.public_key[3] == ES256.ALGORITHM def test_from_registration_encodes_as_unicode(webauthn_dev_server): registration_response = { 'clientDataJSON': CLIENT_DATA_JSON, 'attestationObject': ATTESTATION_OBJECT, } credential = WebAuthnCredential.from_registration(SESSION_STATE, registration_response) serialized_credential = credential.serialize() assert type(serialized_credential['credential_data']) == str assert type(serialized_credential['registration_response']) == str def test_from_registration_handles_library_errors(notify_admin): registration_response = { 'clientDataJSON': CLIENT_DATA_JSON, 'attestationObject': ATTESTATION_OBJECT, } with pytest.raises(RegistrationError) as exc_info: WebAuthnCredential.from_registration(SESSION_STATE, registration_response) assert 'Invalid origin' in str(exc_info.value) def test_from_registration_handles_unsupported_keys(webauthn_dev_server): registration_response = { 'clientDataJSON': CLIENT_DATA_JSON, 'attestationObject': UNSUPPORTED_ATTESTATION_OBJECT, } with pytest.raises(RegistrationError) as exc_info: WebAuthnCredential.from_registration(SESSION_STATE, registration_response) assert 'Encryption algorithm not supported' in str(exc_info.value)
73.625
1,274
0.873986
import base64 import pytest from fido2 import cbor from fido2.cose import ES256 from app.models.webauthn_credential import RegistrationError, WebAuthnCredential _STATE = {'challenge': 'bPzpX3hHQtsp9evyKYkaZtVc9UN07PUdJ22vZUdDp94', 'user_verification': 'discouraged'} CLIENT_DATA_JSON = b'{"type": "webauthn.create", "clientExtensions": {}, "challenge": "bPzpX3hHQtsp9evyKYkaZtVc9UN07PUdJ22vZUdDp94", "origin": "https://webauthn.io"}' ATTESTATION_OBJECT = base64.b64decode(b'o2NmbXRoZmlkby11MmZnYXR0U3RtdKJjc2lnWEgwRgIhAI1qbvWibQos/t3zsTU05IXw1Ek3SDApATok09uc4UBwAiEAv0fB/lgb5Ot3zJ691Vje6iQLAtLhJDiA8zDxaGjcE3hjeDVjgVkCUzCCAk8wggE3oAMCAQICBDxoKU0wDQYJKoZIhvcNAQELBQAwLjEsMCoGA1UEAxMjWXViaWNvIFUyRiBSb290IENBIFNlcmlhbCA0NTcyMDA2MzEwIBcNMTQwODAxMDAwMDAwWhgPMjA1MDA5MDQwMDAwMDBaMDExLzAtBgNVBAMMJll1YmljbyBVMkYgRUUgU2VyaWFsIDIzOTI1NzM0ODExMTE3OTAxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEvd9nk9t3lMNQMXHtLE1FStlzZnUaSLql2fm1ajoggXlrTt8rzXuSehSTEPvEaEdv/FeSqX22L6Aoa8ajIAIOY6M7MDkwIgYJKwYBBAGCxAoCBBUxLjMuNi4xLjQuMS40MTQ4Mi4xLjUwEwYLKwYBBAGC5RwCAQEEBAMCBSAwDQYJKoZIhvcNAQELBQADggEBAKrADVEJfuwVpIazebzEg0D4Z9OXLs5qZ/ukcONgxkRZ8K04QtP/CB5x6olTlxsj+SXArQDCRzEYUgbws6kZKfuRt2a1P+EzUiqDWLjRILSr+3/o7yR7ZP/GpiFKwdm+czb94POoGD+TS1IYdfXj94mAr5cKWx4EKjh210uovu/pLdLjc8xkQciUrXzZpPR9rT2k/q9HkZhHU+NaCJzky+PTyDbq0KKnzqVhWtfkSBCGw3ezZkTS+5lrvOKbIa24lfeTgu7FST5OwTPCFn8HcfWZMXMSD/KNU+iBqJdAwTLPPDRoLLvPTl29weCAIh+HUpmBQd0UltcPOrA/LFvAf61oYXV0aERhdGFYwnSm6pITyZwvdLIkkrMgz0AmKpTBqVCgOX8pJQtghB7wQQAAAAAAAAAAAAAAAAAAAAAAAAAAAECKU1ppjl9gmhHWyDkgHsUvZmhr6oF3/lD3llzLE2SaOSgOGIsIuAQqgp8JQSUu3r/oOaP8RS44dlQjrH+ALfYtpAECAyYhWCAxnqAfESXOYjKUc2WACuXZ3ch0JHxV0VFrrTyjyjIHXCJYIFnx8H87L4bApR4M+hPcV+fHehEOeW+KCyd0H+WGY8s6') UNSUPPORTED_ATTESTATION_OBJECT = base64.b64decode(b'o2NmbXRoZmlkby11MmZnYXR0U3RtdKJjc2lnWEgwRgIhAI1qbvWibQos/t3zsTU05IXw1Ek3SDApATok09uc4UBwAiEAv0fB/lgb5Ot3zJ691Vje6iQLAtLhJDiA8zDxaGjcE3hjeDVjgVkCUzCCAk8wggE3oAMCAQICBDxoKU0wDQYJKoZIhvcNAQELBQAwLjEsMCoGA1UEAxMjWXViaWNvIFUyRiBSb290IENBIFNlcmlhbCA0NTcyMDA2MzEwIBcNMTQwODAxMDAwMDAwWhgPMjA1MDA5MDQwMDAwMDBaMDExLzAtBgNVBAMMJll1YmljbyBVMkYgRUUgU2VyaWFsIDIzOTI1NzM0ODExMTE3OTAxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEvd9nk9t3lMNQMXHtLE1FStlzZnUaSLql2fm1ajoggXlrTt8rzXuSehSTEPvEaEdv/FeSqX22L6Aoa8ajIAIOY6M7MDkwIgYJKwYBBAGCxAoCBBUxLjMuNi4xLjQuMS40MTQ4Mi4xLjUwEwYLKwYBBAGC5RwCAQEEBAMCBSAwDQYJKoZIhvcNAQELBQADggEBAKrADVEJfuwVpIazebzEg0D4Z9OXLs5qZ/ukcONgxkRZ8K04QtP/CB5x6olTlxsj+SXArQDCRzEYUgbws6kZKfuRt2a1P+EzUiqDWLjRILSr+3/o7yR7ZP/GpiFKwdm+czb94POoGD+TS1IYdfXj94mAr5cKWx4EKjh210uovu/pLdLjc8xkQciUrXzZpPR9rT2k/q9HkZhHU+NaCJzky+PTyDbq0KKnzqVhWtfkSBCGw3ezZkTS+5lrvOKbIa24lfeTgu7FST5OwTPCFn8HcfWZMXMSD/KNU+iBqJdAwTLPPDRoLLvPTl29weCAIh+HUpmBQd0UltcPOrA/LFvAf61oYXV0aERhdGFYwnSm6pITyZwvdLIkkrMgz0AmKpTBqVCgOX8pJQtghB7wQQAAAAAAAAAAAAAAAAAAAAAAAAAAAECKU1ppjl9gmhHWyDkgHsUvZmhr6oF3/lD3llzLE2SaOSgOGIsIuAQqgp8JQSUu3r/oOaP8RS44dlQjrH+ALfYtpAECAyUhWCAxnqAfESXOYjKUc2WACuXZ3ch0JHxV0VFrrTyjyjIHXCJYIFnx8H87L4bApR4M+hPcV+fHehEOeW+KCyd0H+WGY8s6') def test_from_registration_verifies_response(webauthn_dev_server): registration_response = { 'clientDataJSON': CLIENT_DATA_JSON, 'attestationObject': ATTESTATION_OBJECT, } credential = WebAuthnCredential.from_registration(SESSION_STATE, registration_response) assert credential.name == 'Unnamed key' assert credential.registration_response == base64.b64encode(cbor.encode(registration_response)).decode('utf-8') credential_data = credential.to_credential_data() assert type(credential_data.credential_id) is bytes assert type(credential_data.aaguid) is bytes assert credential_data.public_key[3] == ES256.ALGORITHM def test_from_registration_encodes_as_unicode(webauthn_dev_server): registration_response = { 'clientDataJSON': CLIENT_DATA_JSON, 'attestationObject': ATTESTATION_OBJECT, } credential = WebAuthnCredential.from_registration(SESSION_STATE, registration_response) serialized_credential = credential.serialize() assert type(serialized_credential['credential_data']) == str assert type(serialized_credential['registration_response']) == str def test_from_registration_handles_library_errors(notify_admin): registration_response = { 'clientDataJSON': CLIENT_DATA_JSON, 'attestationObject': ATTESTATION_OBJECT, } with pytest.raises(RegistrationError) as exc_info: WebAuthnCredential.from_registration(SESSION_STATE, registration_response) assert 'Invalid origin' in str(exc_info.value) def test_from_registration_handles_unsupported_keys(webauthn_dev_server): registration_response = { 'clientDataJSON': CLIENT_DATA_JSON, 'attestationObject': UNSUPPORTED_ATTESTATION_OBJECT, } with pytest.raises(RegistrationError) as exc_info: WebAuthnCredential.from_registration(SESSION_STATE, registration_response) assert 'Encryption algorithm not supported' in str(exc_info.value)
true
true
f727a030df092bb2e0060f668a84075527b879dd
913
py
Python
src/dicom_parser/utils/bids/utils.py
open-dicom/dicom_parser
acc82f6f989a335fd3cf30e716334081ab9ac43b
[ "MIT" ]
6
2021-08-01T17:48:57.000Z
2022-03-07T15:41:26.000Z
src/dicom_parser/utils/bids/utils.py
open-dicom/dicom_parser
acc82f6f989a335fd3cf30e716334081ab9ac43b
[ "MIT" ]
33
2021-08-08T16:09:21.000Z
2022-03-15T15:17:37.000Z
src/dicom_parser/utils/bids/utils.py
open-dicom/dicom_parser
acc82f6f989a335fd3cf30e716334081ab9ac43b
[ "MIT" ]
6
2021-10-19T09:19:22.000Z
2022-03-13T19:26:10.000Z
""" Utilities for the :mod:`dicom_parser.utils.bids` module. """ from typing import Dict, List # A summary of the unique parts (key/value) pairs that make up the appropriate # BIDS-compatible file name by data type. ANATOMICAL_NAME_PARTS: List[str] = ["acq", "ce", "rec", "inv", "run", "part"] DWI_NAME_PARTS: List[str] = ["acq", "dir", "run", "part"] FIELDMAP_NAME_PARTS: List[str] = ["acq", "ce", "dir", "run"] FUNCTIONAL_NAME_PARTS: List[str] = [ "task", "acq", "ce", "rec", "dir", "run", "echo", "part", ] SBREF_NAME_PARTS: List[str] = ["acq", "dir", "run", "part"] NAME_PARTS_BY_DATA_TYPE: Dict[str, List[str]] = { "anat": ANATOMICAL_NAME_PARTS, "func": FUNCTIONAL_NAME_PARTS, "dwi": DWI_NAME_PARTS, "sbref": SBREF_NAME_PARTS, "fmap": FIELDMAP_NAME_PARTS, } BIDS_PATH_TEMPLATE: str = ( "{subject}/{session}/{data_type}/{subject}_{session}{labels}" )
27.666667
78
0.637459
from typing import Dict, List ANATOMICAL_NAME_PARTS: List[str] = ["acq", "ce", "rec", "inv", "run", "part"] DWI_NAME_PARTS: List[str] = ["acq", "dir", "run", "part"] FIELDMAP_NAME_PARTS: List[str] = ["acq", "ce", "dir", "run"] FUNCTIONAL_NAME_PARTS: List[str] = [ "task", "acq", "ce", "rec", "dir", "run", "echo", "part", ] SBREF_NAME_PARTS: List[str] = ["acq", "dir", "run", "part"] NAME_PARTS_BY_DATA_TYPE: Dict[str, List[str]] = { "anat": ANATOMICAL_NAME_PARTS, "func": FUNCTIONAL_NAME_PARTS, "dwi": DWI_NAME_PARTS, "sbref": SBREF_NAME_PARTS, "fmap": FIELDMAP_NAME_PARTS, } BIDS_PATH_TEMPLATE: str = ( "{subject}/{session}/{data_type}/{subject}_{session}{labels}" )
true
true
f727a06b1b074152cadb873d888a24a742788ecb
761
py
Python
cride/users/admin.py
valot3/Cride-API
a9e201942e6eecd479f575733e93ff73e6df573d
[ "MIT" ]
null
null
null
cride/users/admin.py
valot3/Cride-API
a9e201942e6eecd479f575733e93ff73e6df573d
[ "MIT" ]
null
null
null
cride/users/admin.py
valot3/Cride-API
a9e201942e6eecd479f575733e93ff73e6df573d
[ "MIT" ]
null
null
null
"""User models admin""" #Django from django.contrib import admin from django.contrib.auth.admin import UserAdmin #Project from cride.users.models import User, Profile class CustomUserAdmin(UserAdmin): """User model admin.""" list_display = ('email', 'username', 'first_name', 'last_name', 'is_staff', 'is_client') list_filter = ('is_client', 'is_staff', 'created_at', 'modified_at') class ProfileAdmin(admin.ModelAdmin): """Profile model admin.""" list_display = ('user', 'reputation', 'rides_taken', 'rides_offered') search_fields = ('user__username', 'user__email', 'user__first_name', 'user__last_name') list_filter = ('reputation',) admin.site.register(User, CustomUserAdmin) admin.site.register(Profile, ProfileAdmin)
27.178571
92
0.720105
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from cride.users.models import User, Profile class CustomUserAdmin(UserAdmin): list_display = ('email', 'username', 'first_name', 'last_name', 'is_staff', 'is_client') list_filter = ('is_client', 'is_staff', 'created_at', 'modified_at') class ProfileAdmin(admin.ModelAdmin): list_display = ('user', 'reputation', 'rides_taken', 'rides_offered') search_fields = ('user__username', 'user__email', 'user__first_name', 'user__last_name') list_filter = ('reputation',) admin.site.register(User, CustomUserAdmin) admin.site.register(Profile, ProfileAdmin)
true
true
f727a107c1b6bc630f2298f8758fa301408ca175
105
py
Python
wrapcord/__init__.py
nsde/wrapcord
d9a6225085a658a630a9527edb4fa7b991657856
[ "MIT" ]
null
null
null
wrapcord/__init__.py
nsde/wrapcord
d9a6225085a658a630a9527edb4fa7b991657856
[ "MIT" ]
null
null
null
wrapcord/__init__.py
nsde/wrapcord
d9a6225085a658a630a9527edb4fa7b991657856
[ "MIT" ]
null
null
null
from .channel import Channel from .guild import Guild from .message import Message from .user import User
26.25
28
0.819048
from .channel import Channel from .guild import Guild from .message import Message from .user import User
true
true
f727a133e51c2b5e804c815e0c981bdfa6b73676
3,793
py
Python
pyleecan/GUI/Dialog/DMachineSetup/SWSlot/PWSlot15/Gen_PWSlot15.py
IrakozeFD/pyleecan
5a93bd98755d880176c1ce8ac90f36ca1b907055
[ "Apache-2.0" ]
95
2019-01-23T04:19:45.000Z
2022-03-17T18:22:10.000Z
pyleecan/GUI/Dialog/DMachineSetup/SWSlot/PWSlot15/Gen_PWSlot15.py
IrakozeFD/pyleecan
5a93bd98755d880176c1ce8ac90f36ca1b907055
[ "Apache-2.0" ]
366
2019-02-20T07:15:08.000Z
2022-03-31T13:37:23.000Z
pyleecan/GUI/Dialog/DMachineSetup/SWSlot/PWSlot15/Gen_PWSlot15.py
IrakozeFD/pyleecan
5a93bd98755d880176c1ce8ac90f36ca1b907055
[ "Apache-2.0" ]
74
2019-01-24T01:47:31.000Z
2022-02-25T05:44:42.000Z
# -*- coding: utf-8 -*- """File generated according to PWSlot15/gen_list.json WARNING! All changes made in this file will be lost! """ from pyleecan.GUI.Dialog.DMachineSetup.SWSlot.PWSlot15.Ui_PWSlot15 import Ui_PWSlot15 class Gen_PWSlot15(Ui_PWSlot15): def setupUi(self, PWSlot15): """Abstract class to update the widget according to the csv doc""" Ui_PWSlot15.setupUi(self, PWSlot15) # Setup of in_W0 txt = self.tr(u"""Slot isthmus width.""") self.in_W0.setWhatsThis(txt) self.in_W0.setToolTip(txt) # Setup of lf_W0 self.lf_W0.validator().setBottom(0) txt = self.tr(u"""Slot isthmus width.""") self.lf_W0.setWhatsThis(txt) self.lf_W0.setToolTip(txt) # Setup of unit_W0 txt = self.tr(u"""Slot isthmus width.""") self.unit_W0.setWhatsThis(txt) self.unit_W0.setToolTip(txt) # Setup of in_W3 txt = self.tr(u"""Tooth width""") self.in_W3.setWhatsThis(txt) self.in_W3.setToolTip(txt) # Setup of lf_W3 self.lf_W3.validator().setBottom(0) txt = self.tr(u"""Tooth width""") self.lf_W3.setWhatsThis(txt) self.lf_W3.setToolTip(txt) # Setup of unit_W3 txt = self.tr(u"""Tooth width""") self.unit_W3.setWhatsThis(txt) self.unit_W3.setToolTip(txt) # Setup of in_H0 txt = self.tr(u"""Slot isthmus height.""") self.in_H0.setWhatsThis(txt) self.in_H0.setToolTip(txt) # Setup of lf_H0 self.lf_H0.validator().setBottom(0) txt = self.tr(u"""Slot isthmus height.""") self.lf_H0.setWhatsThis(txt) self.lf_H0.setToolTip(txt) # Setup of unit_H0 txt = self.tr(u"""Slot isthmus height.""") self.unit_H0.setWhatsThis(txt) self.unit_H0.setToolTip(txt) # Setup of in_H1 txt = self.tr(u"""Slot intermediate height.""") self.in_H1.setWhatsThis(txt) self.in_H1.setToolTip(txt) # Setup of lf_H1 self.lf_H1.validator().setBottom(0) txt = self.tr(u"""Slot intermediate height.""") self.lf_H1.setWhatsThis(txt) self.lf_H1.setToolTip(txt) # Setup of unit_H1 txt = self.tr(u"""Slot intermediate height.""") self.unit_H1.setWhatsThis(txt) self.unit_H1.setToolTip(txt) # Setup of in_H2 txt = self.tr(u"""Slot height""") self.in_H2.setWhatsThis(txt) self.in_H2.setToolTip(txt) # Setup of lf_H2 self.lf_H2.validator().setBottom(0) txt = self.tr(u"""Slot height""") self.lf_H2.setWhatsThis(txt) self.lf_H2.setToolTip(txt) # Setup of unit_H2 txt = self.tr(u"""Slot height""") self.unit_H2.setWhatsThis(txt) self.unit_H2.setToolTip(txt) # Setup of in_R1 txt = self.tr(u"""Top radius""") self.in_R1.setWhatsThis(txt) self.in_R1.setToolTip(txt) # Setup of lf_R1 self.lf_R1.validator().setBottom(0) txt = self.tr(u"""Top radius""") self.lf_R1.setWhatsThis(txt) self.lf_R1.setToolTip(txt) # Setup of unit_R1 txt = self.tr(u"""Top radius""") self.unit_R1.setWhatsThis(txt) self.unit_R1.setToolTip(txt) # Setup of in_R2 txt = self.tr(u"""Bottom radius""") self.in_R2.setWhatsThis(txt) self.in_R2.setToolTip(txt) # Setup of lf_R2 self.lf_R2.validator().setBottom(0) txt = self.tr(u"""Bottom radius""") self.lf_R2.setWhatsThis(txt) self.lf_R2.setToolTip(txt) # Setup of unit_R2 txt = self.tr(u"""Bottom radius""") self.unit_R2.setWhatsThis(txt) self.unit_R2.setToolTip(txt)
30.837398
85
0.594516
from pyleecan.GUI.Dialog.DMachineSetup.SWSlot.PWSlot15.Ui_PWSlot15 import Ui_PWSlot15 class Gen_PWSlot15(Ui_PWSlot15): def setupUi(self, PWSlot15): Ui_PWSlot15.setupUi(self, PWSlot15) txt = self.tr(u"""Slot isthmus width.""") self.in_W0.setWhatsThis(txt) self.in_W0.setToolTip(txt) self.lf_W0.validator().setBottom(0) txt = self.tr(u"""Slot isthmus width.""") self.lf_W0.setWhatsThis(txt) self.lf_W0.setToolTip(txt) txt = self.tr(u"""Slot isthmus width.""") self.unit_W0.setWhatsThis(txt) self.unit_W0.setToolTip(txt) txt = self.tr(u"""Tooth width""") self.in_W3.setWhatsThis(txt) self.in_W3.setToolTip(txt) self.lf_W3.validator().setBottom(0) txt = self.tr(u"""Tooth width""") self.lf_W3.setWhatsThis(txt) self.lf_W3.setToolTip(txt) txt = self.tr(u"""Tooth width""") self.unit_W3.setWhatsThis(txt) self.unit_W3.setToolTip(txt) txt = self.tr(u"""Slot isthmus height.""") self.in_H0.setWhatsThis(txt) self.in_H0.setToolTip(txt) self.lf_H0.validator().setBottom(0) txt = self.tr(u"""Slot isthmus height.""") self.lf_H0.setWhatsThis(txt) self.lf_H0.setToolTip(txt) txt = self.tr(u"""Slot isthmus height.""") self.unit_H0.setWhatsThis(txt) self.unit_H0.setToolTip(txt) txt = self.tr(u"""Slot intermediate height.""") self.in_H1.setWhatsThis(txt) self.in_H1.setToolTip(txt) self.lf_H1.validator().setBottom(0) txt = self.tr(u"""Slot intermediate height.""") self.lf_H1.setWhatsThis(txt) self.lf_H1.setToolTip(txt) txt = self.tr(u"""Slot intermediate height.""") self.unit_H1.setWhatsThis(txt) self.unit_H1.setToolTip(txt) txt = self.tr(u"""Slot height""") self.in_H2.setWhatsThis(txt) self.in_H2.setToolTip(txt) self.lf_H2.validator().setBottom(0) txt = self.tr(u"""Slot height""") self.lf_H2.setWhatsThis(txt) self.lf_H2.setToolTip(txt) txt = self.tr(u"""Slot height""") self.unit_H2.setWhatsThis(txt) self.unit_H2.setToolTip(txt) txt = self.tr(u"""Top radius""") self.in_R1.setWhatsThis(txt) self.in_R1.setToolTip(txt) self.lf_R1.validator().setBottom(0) txt = self.tr(u"""Top radius""") self.lf_R1.setWhatsThis(txt) self.lf_R1.setToolTip(txt) txt = self.tr(u"""Top radius""") self.unit_R1.setWhatsThis(txt) self.unit_R1.setToolTip(txt) txt = self.tr(u"""Bottom radius""") self.in_R2.setWhatsThis(txt) self.in_R2.setToolTip(txt) self.lf_R2.validator().setBottom(0) txt = self.tr(u"""Bottom radius""") self.lf_R2.setWhatsThis(txt) self.lf_R2.setToolTip(txt) txt = self.tr(u"""Bottom radius""") self.unit_R2.setWhatsThis(txt) self.unit_R2.setToolTip(txt)
true
true
f727a15310a842d4dcb36ff94d72138869d2a3dc
40,610
py
Python
pytorch_lightning/trainer/training_loop.py
MasaYan24/pytorch-lightning
046ac714f6955ed14b831657ea1b7b16bc28ac93
[ "Apache-2.0" ]
1
2021-08-05T01:45:26.000Z
2021-08-05T01:45:26.000Z
pytorch_lightning/trainer/training_loop.py
MasaYan24/pytorch-lightning
046ac714f6955ed14b831657ea1b7b16bc28ac93
[ "Apache-2.0" ]
null
null
null
pytorch_lightning/trainer/training_loop.py
MasaYan24/pytorch-lightning
046ac714f6955ed14b831657ea1b7b16bc28ac93
[ "Apache-2.0" ]
1
2021-02-16T00:47:46.000Z
2021-02-16T00:47:46.000Z
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from contextlib import contextmanager, suppress from copy import copy, deepcopy import numpy as np import torch from pytorch_lightning.callbacks import EarlyStopping from pytorch_lightning.core.memory import ModelSummary from pytorch_lightning.core.optimizer import LightningOptimizer from pytorch_lightning.core.step_result import Result from pytorch_lightning.plugins import ParallelPlugin from pytorch_lightning.trainer.states import RunningStage, TrainerState from pytorch_lightning.trainer.supporters import Accumulator, TensorRunningAccum from pytorch_lightning.utilities import _TPU_AVAILABLE, AMPType, DeviceType, parsing from pytorch_lightning.utilities.distributed import rank_zero_info, rank_zero_warn from pytorch_lightning.utilities.exceptions import MisconfigurationException from pytorch_lightning.utilities.memory import recursive_detach from pytorch_lightning.utilities.model_helpers import is_overridden from pytorch_lightning.utilities.parsing import AttributeDict from pytorch_lightning.utilities.warnings import WarningCache class TrainLoop: def __init__(self, trainer, multiple_trainloader_mode): self.trainer = trainer self.early_stopping_accumulator = None self.checkpoint_accumulator = None self.accumulated_loss = None self.warning_cache = WarningCache() self._teardown_already_run = False self.running_loss = TensorRunningAccum(window_length=20) self.automatic_optimization = True self._curr_step_result = None self._cur_grad_norm_dict = None self._multiple_trainloader_mode = multiple_trainloader_mode self._skip_backward = False self.trainer._multiple_trainloader_mode = multiple_trainloader_mode def on_trainer_init( self, max_epochs, min_epochs, max_steps, min_steps, num_sanity_val_steps, automatic_optimization, weights_summary, ): self.trainer.global_step = 0 self.trainer.current_epoch = 0 self.trainer.interrupted = False self.trainer.should_stop = False self.trainer._state = TrainerState.INITIALIZING self.trainer.total_batch_idx = 0 self.trainer.batch_idx = 0 self.trainer.num_training_batches = 0 self.trainer.train_dataloader = None self.automatic_optimization = automatic_optimization # If neither max_epochs or max_steps is set, then use existing default of max_epochs = 1000 self.trainer.max_epochs = 1000 if (max_epochs is None and max_steps is None) else max_epochs # If neither min_epochs or min_steps is set, then use existing default of min_epochs = 1 self.trainer.min_epochs = 1 if (min_epochs is None and min_steps is None) else min_epochs self.trainer.max_steps = max_steps self.trainer.min_steps = min_steps if num_sanity_val_steps == -1: self.trainer.num_sanity_val_steps = float("inf") else: self.trainer.num_sanity_val_steps = num_sanity_val_steps self.trainer.weights_summary = weights_summary if weights_summary is not None and weights_summary not in ModelSummary.MODES: raise MisconfigurationException( f"`weights_summary` can be None, {', '.join(ModelSummary.MODES)}, got {weights_summary}" ) @property def num_optimizers(self): num_optimizers = len(self.get_optimizers_iterable()) return num_optimizers def should_skip_training(self): should_by_max_steps = self.trainer.max_steps is not None and self.trainer.global_step >= self.trainer.max_steps should_by_epoch = self.trainer.max_epochs is not None and self.trainer.current_epoch >= self.trainer.max_epochs return should_by_max_steps or should_by_epoch or self.trainer.num_training_batches == 0 def on_train_start(self): # hook self.trainer.call_hook("on_train_start") # provide rank to profiler self.trainer.profile_connector.on_train_start(self.trainer) def setup_fit(self, model, train_dataloader, val_dataloaders, datamodule): # clean hparams if hasattr(model, "hparams"): parsing.clean_namespace(model.hparams) # links data to the trainer self.trainer.data_connector.attach_data(model, train_dataloader, val_dataloaders, datamodule) # check that model is configured correctly self.trainer.config_validator.verify_loop_configurations(model) # attach model log function to callback self.trainer.callback_connector.attach_model_logging_functions(model) def on_train_end(self): if self._teardown_already_run: return self._teardown_already_run = True # trigger checkpoint check. need to temporarily decrease the global step to avoid saving duplicates # when a checkpoint was saved at the last step self.trainer.global_step -= 1 self.check_checkpoint_callback(should_update=True, is_last=True) self.trainer.global_step += 1 # hook self.trainer.call_hook("on_train_end") # todo: TPU 8 cores hangs in flush with TensorBoard. Might do for all loggers. # It might be related to xla tensors blocked when moving the cpu # kill loggers if self.trainer.logger is not None and self.trainer.training_type_plugin.should_finalize: self.trainer.logger.finalize("success") # summarize profile results if self.trainer.global_rank == 0: self.trainer.profiler.describe() # give accelerators a chance to finish self.trainer.accelerator_backend.on_train_end() # clear mem if self.trainer._device_type == DeviceType.GPU: model = self.trainer.get_model() model.cpu() torch.cuda.empty_cache() def check_checkpoint_callback(self, should_update, is_last=False): # TODO bake this logic into the ModelCheckpoint callback if should_update and self.trainer.checkpoint_connector.has_trained: callbacks = self.trainer.checkpoint_callbacks if is_last and any(cb.save_last for cb in callbacks): rank_zero_info("Saving latest checkpoint...") model = self.trainer.get_model() for cb in callbacks: cb.on_validation_end(self.trainer, model) def check_early_stopping_callback(self, should_update): # TODO bake this logic into the EarlyStopping callback if should_update and self.trainer.checkpoint_connector.has_trained: callbacks = [c for c in self.trainer.callbacks if isinstance(c, EarlyStopping)] model = self.trainer.get_model() for cb in callbacks: cb.on_validation_end(self.trainer, model) def on_train_epoch_start(self, epoch): # update training progress in trainer self.trainer.current_epoch = epoch model = self.trainer.get_model() # reset train dataloader if epoch != 0 and self.trainer.reload_dataloaders_every_epoch: self.trainer.reset_train_dataloader(model) # todo: specify the possible exception with suppress(Exception): # set seed for distributed sampler (enables shuffling for each epoch) self.trainer.train_dataloader.sampler.set_epoch(epoch) # changing gradient according accumulation_scheduler self.trainer.accumulation_scheduler.on_epoch_start(self.trainer, self.trainer.get_model()) # stores accumulated grad fractions per batch self.accumulated_loss = TensorRunningAccum(window_length=self.trainer.accumulate_grad_batches) # structured result accumulators for callbacks self.early_stopping_accumulator = Accumulator() self.checkpoint_accumulator = Accumulator() # hook self.trainer.call_hook("on_epoch_start") self.trainer.call_hook("on_train_epoch_start") def on_train_batch_end(self, epoch_output, batch_end_outputs, batch, batch_idx, dataloader_idx): # hook self.trainer.call_hook('on_train_batch_end', batch_end_outputs, batch, batch_idx, dataloader_idx) self.trainer.call_hook('on_batch_end') # figure out what to track for epoch end self.track_epoch_end_reduce_metrics(epoch_output, batch_end_outputs) # reset batch logger internals self.trainer.logger_connector.on_train_batch_end() def reset_train_val_dataloaders(self, model): if self.trainer.train_dataloader is None or not self.trainer.reload_dataloaders_every_epoch: self.trainer.reset_train_dataloader(model) if self.trainer.val_dataloaders is None and not self.trainer.reload_dataloaders_every_epoch: self.trainer.reset_val_dataloader(model) def track_epoch_end_reduce_metrics(self, epoch_output, batch_end_outputs): # track the outputs to reduce at the end of the epoch for opt_idx, opt_outputs in enumerate(batch_end_outputs): sample_output = opt_outputs[-1] # decide if we need to reduce at the end of the epoch automatically auto_reduce_tng_result = isinstance(sample_output, Result) and sample_output.should_reduce_on_epoch_end hook_overridden = ( is_overridden("training_epoch_end", model=self.trainer.get_model()) or is_overridden("on_train_epoch_end", model=self.trainer.get_model()) ) # only track when a) it needs to be autoreduced OR b) the user wants to manually reduce on epoch end if not (hook_overridden or auto_reduce_tng_result): continue # with 1 step (no tbptt) don't use a sequence at epoch end if isinstance(opt_outputs, list) and len(opt_outputs) == 1 and not isinstance(opt_outputs[0], Result): opt_outputs = opt_outputs[0] epoch_output[opt_idx].append(opt_outputs) def get_optimizers_iterable(self): """ Generates an iterable with (idx, optimizer) for each optimizer. """ if not self.trainer.optimizer_frequencies: # call training_step once per optimizer return list(enumerate(self.trainer.optimizers)) optimizer_freq_cumsum = np.cumsum(self.trainer.optimizer_frequencies) optimizers_loop_length = optimizer_freq_cumsum[-1] current_place_in_loop = self.trainer.total_batch_idx % optimizers_loop_length # find optimzier index by looking for the first {item > current_place} in the cumsum list opt_idx = np.argmax(optimizer_freq_cumsum > current_place_in_loop) return [[opt_idx, self.trainer.optimizers[opt_idx]]] def on_after_backward(self, training_step_output, batch_idx, untouched_loss): is_result_obj = isinstance(training_step_output, Result) if is_result_obj: training_step_output.detach() else: training_step_output.batch_loss = training_step_output.batch_loss.detach() # insert after step hook self.trainer.call_hook("on_after_backward") # when in dev debugging track the losses self.trainer.dev_debugger.track_train_loss_history(batch_idx, untouched_loss.detach()) def _check_training_step_output(self, training_step_output): if isinstance(training_step_output, torch.Tensor) and not self.automatic_optimization: if training_step_output.grad_fn is None: # TODO: Find why - RuntimeError: Expected to mark a variable ready only once ... raise MisconfigurationException("In manual optimization, `training_step` should not return a Tensor") def training_step(self, split_batch, batch_idx, opt_idx, hiddens): # give the PL module a result for logging model_ref = self.trainer.get_model() with self.trainer.profiler.profile("model_forward"): args = self.build_train_args(split_batch, batch_idx, opt_idx, hiddens) # manually capture logged metrics model_ref._current_fx_name = 'training_step' model_ref._results = Result() with self.trainer.profiler.profile("training_step"): training_step_output = self.trainer.accelerator_backend.training_step(args) self.trainer.accelerator_backend.post_training_step() self.trainer.logger_connector.cache_logged_metrics() self._check_training_step_output(training_step_output) training_step_output = self.trainer.call_hook("training_step_end", training_step_output) training_step_output_for_epoch_end, training_step_output = self._process_training_step_output( training_step_output, split_batch ) is_result_obj = isinstance(training_step_output, Result) if training_step_output_for_epoch_end is None: return None # enable empty loss when using manual opt closure_loss = None untouched_loss = None if self.trainer.train_loop.automatic_optimization: # accumulate loss # (if accumulate_grad_batches = 1 no effect) if is_result_obj: closure_loss = training_step_output.minimize else: closure_loss = training_step_output.batch_loss closure_loss = closure_loss / self.trainer.accumulate_grad_batches # the loss will get scaled for amp. avoid any modifications to it untouched_loss = closure_loss.detach().clone() # result result = AttributeDict( closure_loss=closure_loss, loss=untouched_loss, training_step_output=training_step_output, training_step_output_for_epoch_end=training_step_output_for_epoch_end, hiddens=training_step_output.hiddens, ) return result def _process_training_step_output(self, training_step_output, split_batch): training_step_output_for_epoch_end = training_step_output # enable validation_step return None if training_step_output_for_epoch_end is None: return None, None # ----------------------------------------- # process result return (DEPRECATE in 1.0) # ----------------------------------------- if isinstance(training_step_output, Result): training_step_output_for_epoch_end = self._process_result(training_step_output, split_batch) return training_step_output_for_epoch_end, training_step_output # ----------------------------------------- # process hybrid (1.0) # ----------------------------------------- # no need for these checks in 1.0.0 # TODO: remove checks in 1.0.0 is_tensor = isinstance(training_step_output_for_epoch_end, torch.Tensor) is_1_0_output = is_tensor or ("log" not in training_step_output and "progress_bar" not in training_step_output) if is_1_0_output: return self._process_training_step_output_1_0(training_step_output, split_batch) # ----------------------------------------- # process old dict (deprecate 1.0) # ----------------------------------------- training_step_output = self.trainer.process_dict_result(training_step_output, train=True) training_step_output = AttributeDict( batch_loss=training_step_output[0], pbar_on_batch_end=training_step_output[1], log_metrics=training_step_output[2], callback_metrics=training_step_output[3], hiddens=training_step_output[4], ) # if the user decides to finally reduce things in epoch_end, save raw output without graphs if isinstance(training_step_output_for_epoch_end, torch.Tensor): training_step_output_for_epoch_end = training_step_output_for_epoch_end.detach() else: training_step_output_for_epoch_end = recursive_detach(training_step_output_for_epoch_end) return training_step_output_for_epoch_end, training_step_output def _process_training_step_output_1_0(self, training_step_output, split_batch): result = self.trainer.get_model()._results loss = None hiddens = None # handle dict return if isinstance(training_step_output, dict): loss = training_step_output.pop("loss", None) hiddens = training_step_output.pop("hiddens", None) result["extra"] = training_step_output # handle scalar return elif isinstance(training_step_output, torch.Tensor): loss = training_step_output result["extra"] = {} # map to results under the hood result.minimize = loss result.hiddens = hiddens # track batch for manual reduction with result result.track_batch_size(len(split_batch)) # track metrics without grads for epoch reduction training_step_output_for_epoch_end = copy(result) training_step_output_for_epoch_end.detach() if self.trainer.move_metrics_to_cpu: training_step_output_for_epoch_end.cpu() # what flows back into the system training_step_output = result return training_step_output_for_epoch_end, training_step_output def _process_result(self, training_step_output, split_batch): training_step_output.track_batch_size(len(split_batch)) m = """ TrainResult and EvalResult were deprecated in 0.9.1 and support will drop in 1.0.0. Use self.log and .write from the LightningModule to log metrics and write predictions. training_step can now only return a scalar (for the loss) or a dictionary with anything you want. Option 1: return loss Option 2: return {'loss': loss, 'anything_else': ...} Option 3: return {'loss': loss, 'hiddens': hiddens, 'anything_else': ...} """ rank_zero_warn(m) training_step_output_for_epoch_end = copy(training_step_output) training_step_output_for_epoch_end.detach() return training_step_output_for_epoch_end def optimizer_step(self, optimizer, opt_idx, batch_idx, train_step_and_backward_closure): model_ref = self.trainer.get_model() is_lbfgs = isinstance(optimizer, torch.optim.LBFGS) using_native_amp = self.trainer.amp_backend == AMPType.NATIVE # native amp + lbfgs is a no go right now if using_native_amp and is_lbfgs: raise MisconfigurationException( 'native PyTorch amp and lbfgs are not compatible.' ' To request, please file a Github issue in PyTorch and tag @mcarilli' ) # wraps into LightningOptimizer only for running step optimizer = LightningOptimizer._to_lightning_optimizer(optimizer, self.trainer, opt_idx) # model hook model_ref.optimizer_step( self.trainer.current_epoch, batch_idx, optimizer, opt_idx, train_step_and_backward_closure, on_tpu=self.trainer._device_type == DeviceType.TPU and _TPU_AVAILABLE, using_native_amp=using_native_amp, using_lbfgs=is_lbfgs, ) def on_before_zero_grad(self, optimizer): self.trainer.call_hook('on_before_zero_grad', optimizer) def optimizer_zero_grad(self, batch_idx, optimizer, opt_idx): self.trainer.accelerator_backend.optimizer_zero_grad(self.trainer.current_epoch, batch_idx, optimizer, opt_idx) def track_and_norm_grad(self, optimizer): # track gradient norms grad_norm_dic = self._track_gradient_norm() # clip gradients self.trainer.accelerator_backend.clip_gradients(optimizer, self.trainer.gradient_clip_val) self._cur_grad_norm_dict = grad_norm_dic def _track_gradient_norm(self): grad_norm_dict = {} if (self.trainer.global_step + 1) % self.trainer.log_every_n_steps == 0: if float(self.trainer.track_grad_norm) > 0: model = self.trainer.get_model() grad_norm_dict = model.grad_norm(self.trainer.track_grad_norm) return grad_norm_dict def process_hiddens(self, opt_closure_result): hiddens = opt_closure_result.hiddens if isinstance(opt_closure_result.training_step_output, Result): opt_closure_result.training_step_output_for_epoch_end.drop_hiddens() return hiddens def tbptt_split_batch(self, batch): splits = [batch] if self.trainer.truncated_bptt_steps is not None: model_ref = self.trainer.get_model() with self.trainer.profiler.profile("tbptt_split_batch"): splits = model_ref.tbptt_split_batch(batch, self.trainer.truncated_bptt_steps) return splits def run_training_epoch(self): # modify dataloader if needed (ddp, etc...) train_dataloader = self.trainer.accelerator_backend.process_dataloader(self.trainer.train_dataloader) # track epoch output epoch_output = [[] for _ in range(self.num_optimizers)] train_dataloader = self.trainer.data_connector.get_profiled_train_dataloader(train_dataloader) dataloader_idx = 0 should_check_val = False for batch_idx, (batch, is_last_batch) in train_dataloader: self.trainer.batch_idx = batch_idx # ------------------------------------ # TRAINING_STEP + TRAINING_STEP_END # ------------------------------------ with self.trainer.profiler.profile("run_training_batch"): batch_output = self.run_training_batch(batch, batch_idx, dataloader_idx) # when returning -1 from train_step, we end epoch early if batch_output.signal == -1: break batch_end_outputs = self.process_train_step_outputs( batch_output.training_step_output_for_epoch_end, self.early_stopping_accumulator, self.checkpoint_accumulator, ) # hook # TODO: add outputs to batches self.on_train_batch_end(epoch_output, batch_end_outputs, batch, batch_idx, dataloader_idx) # ----------------------------------------- # SAVE METRICS TO LOGGERS # ----------------------------------------- self.trainer.logger_connector.log_train_step_metrics(batch_output) # ----------------------------------------- # VALIDATE IF NEEDED + CHECKPOINT CALLBACK # ----------------------------------------- should_check_val = self.should_check_val_fx(batch_idx, is_last_batch) if should_check_val: self.trainer.run_evaluation() # reset stage to train self.trainer._set_wide_running_stage(RunningStage.TRAINING) # ----------------------------------------- # SAVE LOGGERS (ie: Tensorboard, etc...) # ----------------------------------------- self.save_loggers_on_train_batch_end() # update LR schedulers monitor_metrics = deepcopy(self.trainer.logger_connector.callback_metrics) self.update_train_loop_lr_schedulers(monitor_metrics=monitor_metrics) self.trainer.checkpoint_connector.has_trained = True # max steps reached, end training if ( self.trainer.max_steps is not None and self.trainer.max_steps == self.trainer.global_step + 1 and self._accumulated_batches_reached() ): break # end epoch early # stop when the flag is changed or we've gone past the amount # requested in the batches if self.trainer.should_stop: break self.trainer.total_batch_idx += 1 # stop epoch if we limited the number of training batches if self._num_training_batches_reached(is_last_batch): break # progress global step according to grads progress self.increment_accumulated_grad_global_step() # epoch end hook self.run_on_epoch_end_hook(epoch_output) # log epoch metrics self.trainer.logger_connector.log_train_epoch_end_metrics( epoch_output, self.checkpoint_accumulator, self.early_stopping_accumulator, self.num_optimizers ) should_check_val = self.should_check_val_fx(batch_idx, is_last_batch, on_epoch=True) if should_check_val: self.trainer.run_evaluation(on_epoch=True) # reset stage to train self.trainer._set_wide_running_stage(RunningStage.TRAINING) should_skip_eval = self.trainer.evaluation_loop.should_skip_evaluation(self.trainer.num_val_batches) should_train_only = self.trainer.disable_validation or should_skip_eval if should_train_only: # update epoch level lr_schedulers self.trainer.optimizer_connector.update_learning_rates(interval='epoch') self.check_checkpoint_callback(True) self.check_early_stopping_callback(True) # increment the global step once # progress global step according to grads progress self.increment_accumulated_grad_global_step() def run_training_batch(self, batch, batch_idx, dataloader_idx): # track grad norms grad_norm_dic = {} # bookkeeping self.trainer.hiddens = None # track all outputs across time and num of optimizers batch_outputs = [[] for _ in range(len(self.get_optimizers_iterable()))] if batch is None: return AttributeDict(signal=0, grad_norm_dic=grad_norm_dic) # hook response = self.trainer.call_hook("on_batch_start") if response == -1: return AttributeDict(signal=-1, grad_norm_dic=grad_norm_dic) # hook response = self.trainer.call_hook("on_train_batch_start", batch, batch_idx, dataloader_idx) if response == -1: return AttributeDict(signal=-1, grad_norm_dic=grad_norm_dic) # lightning module hook splits = self.tbptt_split_batch(batch) for split_idx, split_batch in enumerate(splits): # create an iterable for optimizers and loop over them for opt_idx, optimizer in self.prepare_optimizers(): # toggle model params + set info to logger_connector self.run_train_split_start(split_idx, split_batch, opt_idx, optimizer) if self.should_accumulate(): # For gradient accumulation # ------------------- # calculate loss (train step + train step end) # ------------------- # automatic_optimization=True: perform dpp sync only when performing optimizer_step # automatic_optimization=False: don't block synchronization here with self.block_ddp_sync_behaviour(): self.training_step_and_backward( split_batch, batch_idx, opt_idx, optimizer, self.trainer.hiddens ) batch_outputs = self._process_closure_result( batch_outputs=batch_outputs, opt_idx=opt_idx, ) # ------------------------------ # BACKWARD PASS # ------------------------------ # gradient update with accumulated gradients else: if self.automatic_optimization: def train_step_and_backward_closure(): result = self.training_step_and_backward( split_batch, batch_idx, opt_idx, optimizer, self.trainer.hiddens ) return None if result is None else result.loss # optimizer step self.optimizer_step(optimizer, opt_idx, batch_idx, train_step_and_backward_closure) else: self._curr_step_result = self.training_step( split_batch, batch_idx, opt_idx, self.trainer.hiddens ) if self._curr_step_result is None: # user decided to skip optimization # make sure to zero grad. continue batch_outputs = self._process_closure_result( batch_outputs=batch_outputs, opt_idx=opt_idx, ) # todo: Properly aggregate grad_norm accros opt_idx and split_idx grad_norm_dic = self._cur_grad_norm_dict self._cur_grad_norm_dict = None # update running loss + reset accumulated loss self.update_running_loss() result = AttributeDict( signal=0, grad_norm_dic=grad_norm_dic, training_step_output_for_epoch_end=batch_outputs, ) return result @contextmanager def block_ddp_sync_behaviour(self, should_block_sync: bool = False): """ automatic_optimization = True Blocks ddp sync gradients behaviour on backwards pass. This is useful for skipping sync when accumulating gradients, reducing communication overhead automatic_optimization = False do not block ddp gradient sync when using manual optimization as gradients are needed within the training step Returns: context manager with sync behaviour off """ if ( isinstance(self.trainer.training_type_plugin, ParallelPlugin) and (self.automatic_optimization or should_block_sync) ): with self.trainer.training_type_plugin.block_backward_sync(): yield None else: yield None def _process_closure_result(self, batch_outputs: list, opt_idx: int) -> list: opt_closure_result = self._curr_step_result if opt_closure_result is not None: # cache metrics self.trainer.logger_connector.cache_training_step_metrics(opt_closure_result) # track hiddens self.trainer.hiddens = self.process_hiddens(opt_closure_result) # check if loss or model weights are nan if self.trainer.terminate_on_nan: self.trainer.detect_nan_tensors(opt_closure_result.loss) # track all the outputs across all steps batch_opt_idx = opt_idx if len(batch_outputs) > 1 else 0 batch_outputs[batch_opt_idx].append(opt_closure_result.training_step_output_for_epoch_end) if self.automatic_optimization: # track total loss for logging (avoid mem leaks) self.accumulated_loss.append(opt_closure_result.loss) self._curr_step_result = None return batch_outputs def training_step_and_backward(self, split_batch, batch_idx, opt_idx, optimizer, hiddens): """ wrap the forward step in a closure so second order methods work """ with self.trainer.profiler.profile("training_step_and_backward"): # lightning module hook result = self.training_step(split_batch, batch_idx, opt_idx, hiddens) self._curr_step_result = result if result is None: if self.automatic_optimization: self.warning_cache.warn("training_step returned None if it was on purpose, ignore this warning...") return None if not self._skip_backward and self.trainer.train_loop.automatic_optimization: # backward pass with self.trainer.profiler.profile("model_backward"): self.backward(result, optimizer, opt_idx) # hook - call this hook only # when gradients have finished to accumulate if not self.should_accumulate(): self.on_after_backward(result.training_step_output, batch_idx, result.loss) # check if loss or model weights are nan if self.trainer.terminate_on_nan: self.trainer.detect_nan_tensors(result.loss) if len(self.trainer.optimizers) > 1: # revert back to previous state self.trainer.get_model().untoggle_optimizer(opt_idx) return result def backward(self, result, optimizer, opt_idx, *args, **kwargs): self.trainer.dev_debugger.track_event("backward_call") should_accumulate = self.should_accumulate() # backward can be called manually in the training loop if isinstance(result, torch.Tensor): self.trainer.accelerator_backend.backward(result, optimizer, opt_idx, should_accumulate, *args, **kwargs) else: result.closure_loss = self.trainer.accelerator_backend.backward( result.closure_loss, optimizer, opt_idx, should_accumulate, *args, **kwargs ) if not self.should_accumulate(): # track gradients self.track_and_norm_grad(optimizer=optimizer) def update_train_loop_lr_schedulers(self, monitor_metrics=None): num_accumulated_batches_reached = self._accumulated_batches_reached() num_training_batches_reached = self._num_training_batches_reached() if num_accumulated_batches_reached or num_training_batches_reached: # update lr self.trainer.optimizer_connector.update_learning_rates(interval="step", monitor_metrics=monitor_metrics) def run_on_epoch_end_hook(self, epoch_output): # inform logger the batch loop has finished self.trainer.logger_connector.on_train_epoch_end() self.trainer.call_hook('on_train_epoch_end', epoch_output) self.trainer.call_hook('on_epoch_end') def increment_accumulated_grad_global_step(self): num_accumulated_batches_reached = self._accumulated_batches_reached() num_training_batches_reached = self._num_training_batches_reached() # progress global step according to grads progress if num_accumulated_batches_reached or num_training_batches_reached: self.trainer.global_step += 1 def _accumulated_batches_reached(self): return (self.trainer.batch_idx + 1) % self.trainer.accumulate_grad_batches == 0 def _num_training_batches_reached(self, is_last_batch=False): return (self.trainer.batch_idx + 1) == self.trainer.num_training_batches or is_last_batch def should_accumulate(self): # checks if backward or backward + optimizer step (via closure) accumulation_done = self._accumulated_batches_reached() is_final_batch = self._num_training_batches_reached() return not (accumulation_done or is_final_batch) def should_check_val_fx(self, batch_idx, is_last_batch, on_epoch=False): # decide if we should run validation is_val_check_batch = (batch_idx + 1) % self.trainer.val_check_batch == 0 is_val_check_epoch = (self.trainer.current_epoch + 1) % self.trainer.check_val_every_n_epoch == 0 can_check_val = self.trainer.enable_validation and is_val_check_epoch is_last_batch_for_infinite_dataset = is_last_batch and self.trainer.val_check_batch == float("inf") epoch_end_val_check = self.trainer.val_check_batch == self.trainer.num_training_batches should_check_val = ((is_val_check_batch and epoch_end_val_check) or self.trainer.should_stop or is_last_batch_for_infinite_dataset ) if on_epoch else (is_val_check_batch and not epoch_end_val_check) return should_check_val and can_check_val def build_train_args(self, batch, batch_idx, opt_idx, hiddens): # enable not needing to add opt_idx to training_step args = [batch, batch_idx] if len(self.trainer.optimizers) > 1: if self.trainer.has_arg("training_step", "optimizer_idx"): args.append(opt_idx) else: num_opts = len(self.trainer.optimizers) raise ValueError( f"Your LightningModule defines {num_opts} optimizers but " f'training_step is missing the "optimizer_idx" argument.' ) # pass hiddens if using tbptt if self.trainer.truncated_bptt_steps is not None: args.append(hiddens) return args def save_loggers_on_train_batch_end(self): # when loggers should save to disk should_flush_logs = self.trainer.logger_connector.should_flush_logs if should_flush_logs and self.trainer.is_global_zero and self.trainer.logger is not None: self.trainer.logger.save() def process_train_step_outputs(self, all_train_step_outputs, early_stopping_accumulator, checkpoint_accumulator): """ Figure out what needs to be tracked/logged at the end of the epoch """ # the training step outputs a list per optimizer. The list contains the outputs at each time step # when no TBPTT is used, then the list has 1 item per batch # when TBPTT IS used, then the list has n items (1 per time step) batch_end_outputs = [] for optimizer_idx_outputs in all_train_step_outputs: # extract one representative sample from each time step (1 if no tbptt) and 0th optimizer if len(optimizer_idx_outputs) == 0: continue sample_output = optimizer_idx_outputs[-1] # pull out callback info if available (ie: Results object) if isinstance(sample_output, dict) and "early_stop_on" in sample_output: early_stopping_accumulator.accumulate(sample_output["early_stop_on"]) if isinstance(sample_output, dict) and "checkpoint_on" in sample_output: checkpoint_accumulator.accumulate(sample_output["checkpoint_on"]) batch_end_outputs.append(optimizer_idx_outputs) return batch_end_outputs def prepare_optimizers(self): # in manual optimization we loop over all optimizers at once optimizers = self.get_optimizers_iterable() if not self.automatic_optimization: optimizers = [optimizers[0]] return optimizers def run_train_split_start(self, split_idx, split_batch, opt_idx, optimizer): # set split_idx to trainer for tracking self.trainer.split_idx = split_idx # make sure only the gradients of the current optimizer's parameters are calculated # in the training step to prevent dangling gradients in multiple-optimizer setup. if self.automatic_optimization and len(self.trainer.optimizers) > 1: model = self.trainer.get_model() model.toggle_optimizer(optimizer, opt_idx) # use to track metrics internally self.trainer.logger_connector.on_train_split_start(split_idx, opt_idx, split_batch) def update_running_loss(self): accumulated_loss = self.accumulated_loss.mean() if accumulated_loss is not None: # calculate running loss for display self.running_loss.append(self.accumulated_loss.mean() * self.trainer.accumulate_grad_batches) # reset for next set of accumulated grads self.accumulated_loss.reset()
42.747368
119
0.661241
from contextlib import contextmanager, suppress from copy import copy, deepcopy import numpy as np import torch from pytorch_lightning.callbacks import EarlyStopping from pytorch_lightning.core.memory import ModelSummary from pytorch_lightning.core.optimizer import LightningOptimizer from pytorch_lightning.core.step_result import Result from pytorch_lightning.plugins import ParallelPlugin from pytorch_lightning.trainer.states import RunningStage, TrainerState from pytorch_lightning.trainer.supporters import Accumulator, TensorRunningAccum from pytorch_lightning.utilities import _TPU_AVAILABLE, AMPType, DeviceType, parsing from pytorch_lightning.utilities.distributed import rank_zero_info, rank_zero_warn from pytorch_lightning.utilities.exceptions import MisconfigurationException from pytorch_lightning.utilities.memory import recursive_detach from pytorch_lightning.utilities.model_helpers import is_overridden from pytorch_lightning.utilities.parsing import AttributeDict from pytorch_lightning.utilities.warnings import WarningCache class TrainLoop: def __init__(self, trainer, multiple_trainloader_mode): self.trainer = trainer self.early_stopping_accumulator = None self.checkpoint_accumulator = None self.accumulated_loss = None self.warning_cache = WarningCache() self._teardown_already_run = False self.running_loss = TensorRunningAccum(window_length=20) self.automatic_optimization = True self._curr_step_result = None self._cur_grad_norm_dict = None self._multiple_trainloader_mode = multiple_trainloader_mode self._skip_backward = False self.trainer._multiple_trainloader_mode = multiple_trainloader_mode def on_trainer_init( self, max_epochs, min_epochs, max_steps, min_steps, num_sanity_val_steps, automatic_optimization, weights_summary, ): self.trainer.global_step = 0 self.trainer.current_epoch = 0 self.trainer.interrupted = False self.trainer.should_stop = False self.trainer._state = TrainerState.INITIALIZING self.trainer.total_batch_idx = 0 self.trainer.batch_idx = 0 self.trainer.num_training_batches = 0 self.trainer.train_dataloader = None self.automatic_optimization = automatic_optimization self.trainer.max_epochs = 1000 if (max_epochs is None and max_steps is None) else max_epochs self.trainer.min_epochs = 1 if (min_epochs is None and min_steps is None) else min_epochs self.trainer.max_steps = max_steps self.trainer.min_steps = min_steps if num_sanity_val_steps == -1: self.trainer.num_sanity_val_steps = float("inf") else: self.trainer.num_sanity_val_steps = num_sanity_val_steps self.trainer.weights_summary = weights_summary if weights_summary is not None and weights_summary not in ModelSummary.MODES: raise MisconfigurationException( f"`weights_summary` can be None, {', '.join(ModelSummary.MODES)}, got {weights_summary}" ) @property def num_optimizers(self): num_optimizers = len(self.get_optimizers_iterable()) return num_optimizers def should_skip_training(self): should_by_max_steps = self.trainer.max_steps is not None and self.trainer.global_step >= self.trainer.max_steps should_by_epoch = self.trainer.max_epochs is not None and self.trainer.current_epoch >= self.trainer.max_epochs return should_by_max_steps or should_by_epoch or self.trainer.num_training_batches == 0 def on_train_start(self): self.trainer.call_hook("on_train_start") self.trainer.profile_connector.on_train_start(self.trainer) def setup_fit(self, model, train_dataloader, val_dataloaders, datamodule): if hasattr(model, "hparams"): parsing.clean_namespace(model.hparams) self.trainer.data_connector.attach_data(model, train_dataloader, val_dataloaders, datamodule) self.trainer.config_validator.verify_loop_configurations(model) self.trainer.callback_connector.attach_model_logging_functions(model) def on_train_end(self): if self._teardown_already_run: return self._teardown_already_run = True self.trainer.global_step -= 1 self.check_checkpoint_callback(should_update=True, is_last=True) self.trainer.global_step += 1 self.trainer.call_hook("on_train_end") if self.trainer.logger is not None and self.trainer.training_type_plugin.should_finalize: self.trainer.logger.finalize("success") if self.trainer.global_rank == 0: self.trainer.profiler.describe() self.trainer.accelerator_backend.on_train_end() if self.trainer._device_type == DeviceType.GPU: model = self.trainer.get_model() model.cpu() torch.cuda.empty_cache() def check_checkpoint_callback(self, should_update, is_last=False): if should_update and self.trainer.checkpoint_connector.has_trained: callbacks = self.trainer.checkpoint_callbacks if is_last and any(cb.save_last for cb in callbacks): rank_zero_info("Saving latest checkpoint...") model = self.trainer.get_model() for cb in callbacks: cb.on_validation_end(self.trainer, model) def check_early_stopping_callback(self, should_update): if should_update and self.trainer.checkpoint_connector.has_trained: callbacks = [c for c in self.trainer.callbacks if isinstance(c, EarlyStopping)] model = self.trainer.get_model() for cb in callbacks: cb.on_validation_end(self.trainer, model) def on_train_epoch_start(self, epoch): self.trainer.current_epoch = epoch model = self.trainer.get_model() if epoch != 0 and self.trainer.reload_dataloaders_every_epoch: self.trainer.reset_train_dataloader(model) with suppress(Exception): self.trainer.train_dataloader.sampler.set_epoch(epoch) self.trainer.accumulation_scheduler.on_epoch_start(self.trainer, self.trainer.get_model()) self.accumulated_loss = TensorRunningAccum(window_length=self.trainer.accumulate_grad_batches) self.early_stopping_accumulator = Accumulator() self.checkpoint_accumulator = Accumulator() self.trainer.call_hook("on_epoch_start") self.trainer.call_hook("on_train_epoch_start") def on_train_batch_end(self, epoch_output, batch_end_outputs, batch, batch_idx, dataloader_idx): self.trainer.call_hook('on_train_batch_end', batch_end_outputs, batch, batch_idx, dataloader_idx) self.trainer.call_hook('on_batch_end') self.track_epoch_end_reduce_metrics(epoch_output, batch_end_outputs) self.trainer.logger_connector.on_train_batch_end() def reset_train_val_dataloaders(self, model): if self.trainer.train_dataloader is None or not self.trainer.reload_dataloaders_every_epoch: self.trainer.reset_train_dataloader(model) if self.trainer.val_dataloaders is None and not self.trainer.reload_dataloaders_every_epoch: self.trainer.reset_val_dataloader(model) def track_epoch_end_reduce_metrics(self, epoch_output, batch_end_outputs): for opt_idx, opt_outputs in enumerate(batch_end_outputs): sample_output = opt_outputs[-1] auto_reduce_tng_result = isinstance(sample_output, Result) and sample_output.should_reduce_on_epoch_end hook_overridden = ( is_overridden("training_epoch_end", model=self.trainer.get_model()) or is_overridden("on_train_epoch_end", model=self.trainer.get_model()) ) if not (hook_overridden or auto_reduce_tng_result): continue if isinstance(opt_outputs, list) and len(opt_outputs) == 1 and not isinstance(opt_outputs[0], Result): opt_outputs = opt_outputs[0] epoch_output[opt_idx].append(opt_outputs) def get_optimizers_iterable(self): if not self.trainer.optimizer_frequencies: # call training_step once per optimizer return list(enumerate(self.trainer.optimizers)) optimizer_freq_cumsum = np.cumsum(self.trainer.optimizer_frequencies) optimizers_loop_length = optimizer_freq_cumsum[-1] current_place_in_loop = self.trainer.total_batch_idx % optimizers_loop_length # find optimzier index by looking for the first {item > current_place} in the cumsum list opt_idx = np.argmax(optimizer_freq_cumsum > current_place_in_loop) return [[opt_idx, self.trainer.optimizers[opt_idx]]] def on_after_backward(self, training_step_output, batch_idx, untouched_loss): is_result_obj = isinstance(training_step_output, Result) if is_result_obj: training_step_output.detach() else: training_step_output.batch_loss = training_step_output.batch_loss.detach() # insert after step hook self.trainer.call_hook("on_after_backward") # when in dev debugging track the losses self.trainer.dev_debugger.track_train_loss_history(batch_idx, untouched_loss.detach()) def _check_training_step_output(self, training_step_output): if isinstance(training_step_output, torch.Tensor) and not self.automatic_optimization: if training_step_output.grad_fn is None: # TODO: Find why - RuntimeError: Expected to mark a variable ready only once ... raise MisconfigurationException("In manual optimization, `training_step` should not return a Tensor") def training_step(self, split_batch, batch_idx, opt_idx, hiddens): # give the PL module a result for logging model_ref = self.trainer.get_model() with self.trainer.profiler.profile("model_forward"): args = self.build_train_args(split_batch, batch_idx, opt_idx, hiddens) # manually capture logged metrics model_ref._current_fx_name = 'training_step' model_ref._results = Result() with self.trainer.profiler.profile("training_step"): training_step_output = self.trainer.accelerator_backend.training_step(args) self.trainer.accelerator_backend.post_training_step() self.trainer.logger_connector.cache_logged_metrics() self._check_training_step_output(training_step_output) training_step_output = self.trainer.call_hook("training_step_end", training_step_output) training_step_output_for_epoch_end, training_step_output = self._process_training_step_output( training_step_output, split_batch ) is_result_obj = isinstance(training_step_output, Result) if training_step_output_for_epoch_end is None: return None # enable empty loss when using manual opt closure_loss = None untouched_loss = None if self.trainer.train_loop.automatic_optimization: # accumulate loss # (if accumulate_grad_batches = 1 no effect) if is_result_obj: closure_loss = training_step_output.minimize else: closure_loss = training_step_output.batch_loss closure_loss = closure_loss / self.trainer.accumulate_grad_batches # the loss will get scaled for amp. avoid any modifications to it untouched_loss = closure_loss.detach().clone() # result result = AttributeDict( closure_loss=closure_loss, loss=untouched_loss, training_step_output=training_step_output, training_step_output_for_epoch_end=training_step_output_for_epoch_end, hiddens=training_step_output.hiddens, ) return result def _process_training_step_output(self, training_step_output, split_batch): training_step_output_for_epoch_end = training_step_output # enable validation_step return None if training_step_output_for_epoch_end is None: return None, None # ----------------------------------------- # process result return (DEPRECATE in 1.0) # ----------------------------------------- if isinstance(training_step_output, Result): training_step_output_for_epoch_end = self._process_result(training_step_output, split_batch) return training_step_output_for_epoch_end, training_step_output # ----------------------------------------- # process hybrid (1.0) # ----------------------------------------- # no need for these checks in 1.0.0 # TODO: remove checks in 1.0.0 is_tensor = isinstance(training_step_output_for_epoch_end, torch.Tensor) is_1_0_output = is_tensor or ("log" not in training_step_output and "progress_bar" not in training_step_output) if is_1_0_output: return self._process_training_step_output_1_0(training_step_output, split_batch) # ----------------------------------------- # process old dict (deprecate 1.0) # ----------------------------------------- training_step_output = self.trainer.process_dict_result(training_step_output, train=True) training_step_output = AttributeDict( batch_loss=training_step_output[0], pbar_on_batch_end=training_step_output[1], log_metrics=training_step_output[2], callback_metrics=training_step_output[3], hiddens=training_step_output[4], ) # if the user decides to finally reduce things in epoch_end, save raw output without graphs if isinstance(training_step_output_for_epoch_end, torch.Tensor): training_step_output_for_epoch_end = training_step_output_for_epoch_end.detach() else: training_step_output_for_epoch_end = recursive_detach(training_step_output_for_epoch_end) return training_step_output_for_epoch_end, training_step_output def _process_training_step_output_1_0(self, training_step_output, split_batch): result = self.trainer.get_model()._results loss = None hiddens = None # handle dict return if isinstance(training_step_output, dict): loss = training_step_output.pop("loss", None) hiddens = training_step_output.pop("hiddens", None) result["extra"] = training_step_output # handle scalar return elif isinstance(training_step_output, torch.Tensor): loss = training_step_output result["extra"] = {} # map to results under the hood result.minimize = loss result.hiddens = hiddens # track batch for manual reduction with result result.track_batch_size(len(split_batch)) # track metrics without grads for epoch reduction training_step_output_for_epoch_end = copy(result) training_step_output_for_epoch_end.detach() if self.trainer.move_metrics_to_cpu: training_step_output_for_epoch_end.cpu() # what flows back into the system training_step_output = result return training_step_output_for_epoch_end, training_step_output def _process_result(self, training_step_output, split_batch): training_step_output.track_batch_size(len(split_batch)) m = """ TrainResult and EvalResult were deprecated in 0.9.1 and support will drop in 1.0.0. Use self.log and .write from the LightningModule to log metrics and write predictions. training_step can now only return a scalar (for the loss) or a dictionary with anything you want. Option 1: return loss Option 2: return {'loss': loss, 'anything_else': ...} Option 3: return {'loss': loss, 'hiddens': hiddens, 'anything_else': ...} """ rank_zero_warn(m) training_step_output_for_epoch_end = copy(training_step_output) training_step_output_for_epoch_end.detach() return training_step_output_for_epoch_end def optimizer_step(self, optimizer, opt_idx, batch_idx, train_step_and_backward_closure): model_ref = self.trainer.get_model() is_lbfgs = isinstance(optimizer, torch.optim.LBFGS) using_native_amp = self.trainer.amp_backend == AMPType.NATIVE # native amp + lbfgs is a no go right now if using_native_amp and is_lbfgs: raise MisconfigurationException( 'native PyTorch amp and lbfgs are not compatible.' ' To request, please file a Github issue in PyTorch and tag @mcarilli' ) # wraps into LightningOptimizer only for running step optimizer = LightningOptimizer._to_lightning_optimizer(optimizer, self.trainer, opt_idx) # model hook model_ref.optimizer_step( self.trainer.current_epoch, batch_idx, optimizer, opt_idx, train_step_and_backward_closure, on_tpu=self.trainer._device_type == DeviceType.TPU and _TPU_AVAILABLE, using_native_amp=using_native_amp, using_lbfgs=is_lbfgs, ) def on_before_zero_grad(self, optimizer): self.trainer.call_hook('on_before_zero_grad', optimizer) def optimizer_zero_grad(self, batch_idx, optimizer, opt_idx): self.trainer.accelerator_backend.optimizer_zero_grad(self.trainer.current_epoch, batch_idx, optimizer, opt_idx) def track_and_norm_grad(self, optimizer): # track gradient norms grad_norm_dic = self._track_gradient_norm() # clip gradients self.trainer.accelerator_backend.clip_gradients(optimizer, self.trainer.gradient_clip_val) self._cur_grad_norm_dict = grad_norm_dic def _track_gradient_norm(self): grad_norm_dict = {} if (self.trainer.global_step + 1) % self.trainer.log_every_n_steps == 0: if float(self.trainer.track_grad_norm) > 0: model = self.trainer.get_model() grad_norm_dict = model.grad_norm(self.trainer.track_grad_norm) return grad_norm_dict def process_hiddens(self, opt_closure_result): hiddens = opt_closure_result.hiddens if isinstance(opt_closure_result.training_step_output, Result): opt_closure_result.training_step_output_for_epoch_end.drop_hiddens() return hiddens def tbptt_split_batch(self, batch): splits = [batch] if self.trainer.truncated_bptt_steps is not None: model_ref = self.trainer.get_model() with self.trainer.profiler.profile("tbptt_split_batch"): splits = model_ref.tbptt_split_batch(batch, self.trainer.truncated_bptt_steps) return splits def run_training_epoch(self): # modify dataloader if needed (ddp, etc...) train_dataloader = self.trainer.accelerator_backend.process_dataloader(self.trainer.train_dataloader) # track epoch output epoch_output = [[] for _ in range(self.num_optimizers)] train_dataloader = self.trainer.data_connector.get_profiled_train_dataloader(train_dataloader) dataloader_idx = 0 should_check_val = False for batch_idx, (batch, is_last_batch) in train_dataloader: self.trainer.batch_idx = batch_idx # ------------------------------------ # TRAINING_STEP + TRAINING_STEP_END # ------------------------------------ with self.trainer.profiler.profile("run_training_batch"): batch_output = self.run_training_batch(batch, batch_idx, dataloader_idx) # when returning -1 from train_step, we end epoch early if batch_output.signal == -1: break batch_end_outputs = self.process_train_step_outputs( batch_output.training_step_output_for_epoch_end, self.early_stopping_accumulator, self.checkpoint_accumulator, ) # hook # TODO: add outputs to batches self.on_train_batch_end(epoch_output, batch_end_outputs, batch, batch_idx, dataloader_idx) # ----------------------------------------- # SAVE METRICS TO LOGGERS # ----------------------------------------- self.trainer.logger_connector.log_train_step_metrics(batch_output) # ----------------------------------------- # VALIDATE IF NEEDED + CHECKPOINT CALLBACK # ----------------------------------------- should_check_val = self.should_check_val_fx(batch_idx, is_last_batch) if should_check_val: self.trainer.run_evaluation() # reset stage to train self.trainer._set_wide_running_stage(RunningStage.TRAINING) # ----------------------------------------- # SAVE LOGGERS (ie: Tensorboard, etc...) # ----------------------------------------- self.save_loggers_on_train_batch_end() # update LR schedulers monitor_metrics = deepcopy(self.trainer.logger_connector.callback_metrics) self.update_train_loop_lr_schedulers(monitor_metrics=monitor_metrics) self.trainer.checkpoint_connector.has_trained = True # max steps reached, end training if ( self.trainer.max_steps is not None and self.trainer.max_steps == self.trainer.global_step + 1 and self._accumulated_batches_reached() ): break # end epoch early # stop when the flag is changed or we've gone past the amount if self.trainer.should_stop: break self.trainer.total_batch_idx += 1 if self._num_training_batches_reached(is_last_batch): break self.increment_accumulated_grad_global_step() self.run_on_epoch_end_hook(epoch_output) self.trainer.logger_connector.log_train_epoch_end_metrics( epoch_output, self.checkpoint_accumulator, self.early_stopping_accumulator, self.num_optimizers ) should_check_val = self.should_check_val_fx(batch_idx, is_last_batch, on_epoch=True) if should_check_val: self.trainer.run_evaluation(on_epoch=True) self.trainer._set_wide_running_stage(RunningStage.TRAINING) should_skip_eval = self.trainer.evaluation_loop.should_skip_evaluation(self.trainer.num_val_batches) should_train_only = self.trainer.disable_validation or should_skip_eval if should_train_only: self.trainer.optimizer_connector.update_learning_rates(interval='epoch') self.check_checkpoint_callback(True) self.check_early_stopping_callback(True) self.increment_accumulated_grad_global_step() def run_training_batch(self, batch, batch_idx, dataloader_idx): grad_norm_dic = {} self.trainer.hiddens = None batch_outputs = [[] for _ in range(len(self.get_optimizers_iterable()))] if batch is None: return AttributeDict(signal=0, grad_norm_dic=grad_norm_dic) response = self.trainer.call_hook("on_batch_start") if response == -1: return AttributeDict(signal=-1, grad_norm_dic=grad_norm_dic) response = self.trainer.call_hook("on_train_batch_start", batch, batch_idx, dataloader_idx) if response == -1: return AttributeDict(signal=-1, grad_norm_dic=grad_norm_dic) splits = self.tbptt_split_batch(batch) for split_idx, split_batch in enumerate(splits): for opt_idx, optimizer in self.prepare_optimizers(): self.run_train_split_start(split_idx, split_batch, opt_idx, optimizer) if self.should_accumulate(): with self.block_ddp_sync_behaviour(): self.training_step_and_backward( split_batch, batch_idx, opt_idx, optimizer, self.trainer.hiddens ) batch_outputs = self._process_closure_result( batch_outputs=batch_outputs, opt_idx=opt_idx, ) # ------------------------------ # BACKWARD PASS # ------------------------------ # gradient update with accumulated gradients else: if self.automatic_optimization: def train_step_and_backward_closure(): result = self.training_step_and_backward( split_batch, batch_idx, opt_idx, optimizer, self.trainer.hiddens ) return None if result is None else result.loss # optimizer step self.optimizer_step(optimizer, opt_idx, batch_idx, train_step_and_backward_closure) else: self._curr_step_result = self.training_step( split_batch, batch_idx, opt_idx, self.trainer.hiddens ) if self._curr_step_result is None: # user decided to skip optimization # make sure to zero grad. continue batch_outputs = self._process_closure_result( batch_outputs=batch_outputs, opt_idx=opt_idx, ) # todo: Properly aggregate grad_norm accros opt_idx and split_idx grad_norm_dic = self._cur_grad_norm_dict self._cur_grad_norm_dict = None # update running loss + reset accumulated loss self.update_running_loss() result = AttributeDict( signal=0, grad_norm_dic=grad_norm_dic, training_step_output_for_epoch_end=batch_outputs, ) return result @contextmanager def block_ddp_sync_behaviour(self, should_block_sync: bool = False): if ( isinstance(self.trainer.training_type_plugin, ParallelPlugin) and (self.automatic_optimization or should_block_sync) ): with self.trainer.training_type_plugin.block_backward_sync(): yield None else: yield None def _process_closure_result(self, batch_outputs: list, opt_idx: int) -> list: opt_closure_result = self._curr_step_result if opt_closure_result is not None: # cache metrics self.trainer.logger_connector.cache_training_step_metrics(opt_closure_result) # track hiddens self.trainer.hiddens = self.process_hiddens(opt_closure_result) # check if loss or model weights are nan if self.trainer.terminate_on_nan: self.trainer.detect_nan_tensors(opt_closure_result.loss) # track all the outputs across all steps batch_opt_idx = opt_idx if len(batch_outputs) > 1 else 0 batch_outputs[batch_opt_idx].append(opt_closure_result.training_step_output_for_epoch_end) if self.automatic_optimization: # track total loss for logging (avoid mem leaks) self.accumulated_loss.append(opt_closure_result.loss) self._curr_step_result = None return batch_outputs def training_step_and_backward(self, split_batch, batch_idx, opt_idx, optimizer, hiddens): with self.trainer.profiler.profile("training_step_and_backward"): # lightning module hook result = self.training_step(split_batch, batch_idx, opt_idx, hiddens) self._curr_step_result = result if result is None: if self.automatic_optimization: self.warning_cache.warn("training_step returned None if it was on purpose, ignore this warning...") return None if not self._skip_backward and self.trainer.train_loop.automatic_optimization: # backward pass with self.trainer.profiler.profile("model_backward"): self.backward(result, optimizer, opt_idx) # hook - call this hook only # when gradients have finished to accumulate if not self.should_accumulate(): self.on_after_backward(result.training_step_output, batch_idx, result.loss) # check if loss or model weights are nan if self.trainer.terminate_on_nan: self.trainer.detect_nan_tensors(result.loss) if len(self.trainer.optimizers) > 1: # revert back to previous state self.trainer.get_model().untoggle_optimizer(opt_idx) return result def backward(self, result, optimizer, opt_idx, *args, **kwargs): self.trainer.dev_debugger.track_event("backward_call") should_accumulate = self.should_accumulate() # backward can be called manually in the training loop if isinstance(result, torch.Tensor): self.trainer.accelerator_backend.backward(result, optimizer, opt_idx, should_accumulate, *args, **kwargs) else: result.closure_loss = self.trainer.accelerator_backend.backward( result.closure_loss, optimizer, opt_idx, should_accumulate, *args, **kwargs ) if not self.should_accumulate(): # track gradients self.track_and_norm_grad(optimizer=optimizer) def update_train_loop_lr_schedulers(self, monitor_metrics=None): num_accumulated_batches_reached = self._accumulated_batches_reached() num_training_batches_reached = self._num_training_batches_reached() if num_accumulated_batches_reached or num_training_batches_reached: # update lr self.trainer.optimizer_connector.update_learning_rates(interval="step", monitor_metrics=monitor_metrics) def run_on_epoch_end_hook(self, epoch_output): # inform logger the batch loop has finished self.trainer.logger_connector.on_train_epoch_end() self.trainer.call_hook('on_train_epoch_end', epoch_output) self.trainer.call_hook('on_epoch_end') def increment_accumulated_grad_global_step(self): num_accumulated_batches_reached = self._accumulated_batches_reached() num_training_batches_reached = self._num_training_batches_reached() # progress global step according to grads progress if num_accumulated_batches_reached or num_training_batches_reached: self.trainer.global_step += 1 def _accumulated_batches_reached(self): return (self.trainer.batch_idx + 1) % self.trainer.accumulate_grad_batches == 0 def _num_training_batches_reached(self, is_last_batch=False): return (self.trainer.batch_idx + 1) == self.trainer.num_training_batches or is_last_batch def should_accumulate(self): # checks if backward or backward + optimizer step (via closure) accumulation_done = self._accumulated_batches_reached() is_final_batch = self._num_training_batches_reached() return not (accumulation_done or is_final_batch) def should_check_val_fx(self, batch_idx, is_last_batch, on_epoch=False): # decide if we should run validation is_val_check_batch = (batch_idx + 1) % self.trainer.val_check_batch == 0 is_val_check_epoch = (self.trainer.current_epoch + 1) % self.trainer.check_val_every_n_epoch == 0 can_check_val = self.trainer.enable_validation and is_val_check_epoch is_last_batch_for_infinite_dataset = is_last_batch and self.trainer.val_check_batch == float("inf") epoch_end_val_check = self.trainer.val_check_batch == self.trainer.num_training_batches should_check_val = ((is_val_check_batch and epoch_end_val_check) or self.trainer.should_stop or is_last_batch_for_infinite_dataset ) if on_epoch else (is_val_check_batch and not epoch_end_val_check) return should_check_val and can_check_val def build_train_args(self, batch, batch_idx, opt_idx, hiddens): # enable not needing to add opt_idx to training_step args = [batch, batch_idx] if len(self.trainer.optimizers) > 1: if self.trainer.has_arg("training_step", "optimizer_idx"): args.append(opt_idx) else: num_opts = len(self.trainer.optimizers) raise ValueError( f"Your LightningModule defines {num_opts} optimizers but " f'training_step is missing the "optimizer_idx" argument.' ) # pass hiddens if using tbptt if self.trainer.truncated_bptt_steps is not None: args.append(hiddens) return args def save_loggers_on_train_batch_end(self): # when loggers should save to disk should_flush_logs = self.trainer.logger_connector.should_flush_logs if should_flush_logs and self.trainer.is_global_zero and self.trainer.logger is not None: self.trainer.logger.save() def process_train_step_outputs(self, all_train_step_outputs, early_stopping_accumulator, checkpoint_accumulator): # the training step outputs a list per optimizer. The list contains the outputs at each time step # when no TBPTT is used, then the list has 1 item per batch # when TBPTT IS used, then the list has n items (1 per time step) batch_end_outputs = [] for optimizer_idx_outputs in all_train_step_outputs: # extract one representative sample from each time step (1 if no tbptt) and 0th optimizer if len(optimizer_idx_outputs) == 0: continue sample_output = optimizer_idx_outputs[-1] # pull out callback info if available (ie: Results object) if isinstance(sample_output, dict) and "early_stop_on" in sample_output: early_stopping_accumulator.accumulate(sample_output["early_stop_on"]) if isinstance(sample_output, dict) and "checkpoint_on" in sample_output: checkpoint_accumulator.accumulate(sample_output["checkpoint_on"]) batch_end_outputs.append(optimizer_idx_outputs) return batch_end_outputs def prepare_optimizers(self): # in manual optimization we loop over all optimizers at once optimizers = self.get_optimizers_iterable() if not self.automatic_optimization: optimizers = [optimizers[0]] return optimizers def run_train_split_start(self, split_idx, split_batch, opt_idx, optimizer): # set split_idx to trainer for tracking self.trainer.split_idx = split_idx # make sure only the gradients of the current optimizer's parameters are calculated if self.automatic_optimization and len(self.trainer.optimizers) > 1: model = self.trainer.get_model() model.toggle_optimizer(optimizer, opt_idx) self.trainer.logger_connector.on_train_split_start(split_idx, opt_idx, split_batch) def update_running_loss(self): accumulated_loss = self.accumulated_loss.mean() if accumulated_loss is not None: self.running_loss.append(self.accumulated_loss.mean() * self.trainer.accumulate_grad_batches) self.accumulated_loss.reset()
true
true
f727a25388ee496e5f885a90c81f3d667b3f2d2c
478
py
Python
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/binding/options.py
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/binding/options.py
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/binding/options.py
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
from . import ffi from .common import _encode_string from ctypes import c_char_p def set_option(name, option): """ Set the given LLVM "command-line" option. For example set_option("test", "-debug-pass=Structure") would display all optimization passes when generating code. """ ffi.lib.LLVMPY_SetCommandLine(_encode_string(name), _encode_string(option)) ffi.lib.LLVMPY_SetCommandLine.argtypes = [c_char_p, c_char_p]
26.555556
73
0.692469
from . import ffi from .common import _encode_string from ctypes import c_char_p def set_option(name, option): ffi.lib.LLVMPY_SetCommandLine(_encode_string(name), _encode_string(option)) ffi.lib.LLVMPY_SetCommandLine.argtypes = [c_char_p, c_char_p]
true
true
f727a288f380466a672dfe1936fa261ebf099560
2,761
py
Python
utils.py
gurbaaz27/fb-ai3
8c294845594ea3e3dce3922385de34b77d8e3dad
[ "MIT" ]
null
null
null
utils.py
gurbaaz27/fb-ai3
8c294845594ea3e3dce3922385de34b77d8e3dad
[ "MIT" ]
null
null
null
utils.py
gurbaaz27/fb-ai3
8c294845594ea3e3dce3922385de34b77d8e3dad
[ "MIT" ]
null
null
null
import pyaudio import wave from wit import Wit class Speech2Intent: def __init__(self, access_token): self.client = Wit(access_token) self.headers = {'authorization': 'Bearer '+ access_token, 'Content-Type': 'audio/wav'} def recognize_speech(self, AUDIO_FILENAME, num_seconds = 4): self.record_audio(num_seconds, AUDIO_FILENAME) # record audio of specified length in specified audio file audio = self.read_audio(AUDIO_FILENAME) # reading audio text = self.client.speech(audio, self.headers)['text'] return self.client.message(text)['intents'][0]['name'] def record_audio(self,RECORD_SECONDS, WAVE_OUTPUT_FILENAME): #--------- SETTING PARAMS FOR OUR AUDIO FILE ------------# FORMAT = pyaudio.paInt16 # format of wave CHANNELS = 2 # no. of audio channels RATE = 44100 # frame rate CHUNK = 1024 # frames per audio sample #--------------------------------------------------------# # creating PyAudio object audio = pyaudio.PyAudio() # open a new stream for microphone # It creates a PortAudio Stream Wrapper class object stream = audio.open(format=FORMAT,channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) #----------------- start of recording -------------------# print("Listening...") # list to save all audio frames frames = [] for i in range(int(RATE / CHUNK * RECORD_SECONDS)): # read audio stream from microphone data = stream.read(CHUNK) # append audio data to frames list frames.append(data) #------------------ end of recording --------------------# print("Finished listening.") stream.stop_stream() # stop the stream object stream.close() # close the stream object audio.terminate() # terminate PortAudio #------------------ saving audio ------------------------# # create wave file object waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb') # settings for wave file object waveFile.setnchannels(CHANNELS) waveFile.setsampwidth(audio.get_sample_size(FORMAT)) waveFile.setframerate(RATE) waveFile.writeframes(b''.join(frames)) # closing the wave file object waveFile.close() def read_audio(self, WAVE_FILENAME): with open(WAVE_FILENAME, 'rb') as f: audio = f.read() return audio
33.26506
114
0.532054
import pyaudio import wave from wit import Wit class Speech2Intent: def __init__(self, access_token): self.client = Wit(access_token) self.headers = {'authorization': 'Bearer '+ access_token, 'Content-Type': 'audio/wav'} def recognize_speech(self, AUDIO_FILENAME, num_seconds = 4): self.record_audio(num_seconds, AUDIO_FILENAME) audio = self.read_audio(AUDIO_FILENAME) text = self.client.speech(audio, self.headers)['text'] return self.client.message(text)['intents'][0]['name'] def record_audio(self,RECORD_SECONDS, WAVE_OUTPUT_FILENAME): FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 CHUNK = 1024 audio = pyaudio.PyAudio() stream = audio.open(format=FORMAT,channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) print("Listening...") frames = [] for i in range(int(RATE / CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data) print("Finished listening.") stream.stop_stream() stream.close() audio.terminate() waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb') waveFile.setnchannels(CHANNELS) waveFile.setsampwidth(audio.get_sample_size(FORMAT)) waveFile.setframerate(RATE) waveFile.writeframes(b''.join(frames)) waveFile.close() def read_audio(self, WAVE_FILENAME): with open(WAVE_FILENAME, 'rb') as f: audio = f.read() return audio
true
true
f727a2fc3479a82a78afc6c257c0409a5c9b4b20
330
py
Python
Hello_Python/class_electricalcar.py
JaydenYL/Projects
b51c0476f7be80f0b0d6aa84592966ecb4343d76
[ "MIT" ]
5
2021-09-06T04:27:56.000Z
2021-12-14T14:50:27.000Z
Hello_Python/class_electricalcar.py
JaydenYL/Projects
b51c0476f7be80f0b0d6aa84592966ecb4343d76
[ "MIT" ]
null
null
null
Hello_Python/class_electricalcar.py
JaydenYL/Projects
b51c0476f7be80f0b0d6aa84592966ecb4343d76
[ "MIT" ]
null
null
null
from class_car import car class electrical_car(car): def __init__(self, make, model,year): super().__init__(make, model, year) self.battery_volume = 70 # KWh def describe_battery(self): description = 'This car has a '+str(self.battery_volume)+' KWh battery . ' return description.title()
33
82
0.663636
from class_car import car class electrical_car(car): def __init__(self, make, model,year): super().__init__(make, model, year) self.battery_volume = 70 def describe_battery(self): description = 'This car has a '+str(self.battery_volume)+' KWh battery . ' return description.title()
true
true
f727a38e124401ba01468b18ed046aa832af9abd
1,461
py
Python
backend/berkeleytime/config/semesters/fall2017.py
Boomaa23/berkeleytime
f4c3f41025576056953fb944f5e978df43fa9cdc
[ "MIT" ]
21
2021-03-01T00:31:23.000Z
2022-03-12T06:11:46.000Z
backend/berkeleytime/config/semesters/fall2017.py
Boomaa23/berkeleytime
f4c3f41025576056953fb944f5e978df43fa9cdc
[ "MIT" ]
28
2021-04-07T19:02:37.000Z
2022-03-27T19:11:21.000Z
backend/berkeleytime/config/semesters/fall2017.py
Boomaa23/berkeleytime
f4c3f41025576056953fb944f5e978df43fa9cdc
[ "MIT" ]
4
2021-04-19T00:42:00.000Z
2021-11-30T06:29:59.000Z
"""Configurations for Fall 2016.""" from berkeleytime.config.finals.semesters.fall2017 import * import datetime CURRENT_SEMESTER = 'fall' CURRENT_YEAR = '2017' CURRENT_SEMESTER_DISPLAY = 'Fall 2017' # SIS API Keys SIS_TERM_ID = 2178 TELEBEARS = { 'phase1_start': datetime.datetime(2017, 4, 18), 'phase2_start': datetime.datetime(2017, 7, 18), 'phase1_end': datetime.datetime(2017, 7, 15), 'phase2_end': datetime.datetime(2017, 8, 14), 'adj_start': datetime.datetime(2017, 8, 15), } # Please don't edit anything below this line unless you know what you are doing TELEBEARS_JSON = { 'phase1_start_date': TELEBEARS['phase1_start'].strftime('%m/%d/%Y-%H:%M:%S'), 'phase1_end_date': TELEBEARS['phase1_end'].strftime('%m/%d/%Y-%H:%M:%S'), 'phase1_start_day': 1, 'phase1_end_date': (TELEBEARS['phase1_end'] - TELEBEARS['phase1_start']).days + 1, 'phase2_start_date': TELEBEARS['phase2_start'].strftime('%m/%d/%Y-%H:%M:%S'), 'phase2_end_date': TELEBEARS['phase2_end'].strftime('%m/%d/%Y-%H:%M:%S'), 'phase2_start_day': (TELEBEARS['phase2_start'] - TELEBEARS['phase1_start']).days + 1, 'phase2_end_date': (TELEBEARS['phase2_end'] - TELEBEARS['phase1_start']).days + 1, 'adj_start_date': TELEBEARS['adj_start'].strftime('%m/%d/%Y-%H:%M:%S'), 'adj_start_day': (TELEBEARS['adj_start'] - TELEBEARS['phase1_start']).days + 1, } TELEBEARS_ALREADY_STARTED = datetime.datetime.now() >= TELEBEARS['phase1_start']
40.583333
89
0.687885
from berkeleytime.config.finals.semesters.fall2017 import * import datetime CURRENT_SEMESTER = 'fall' CURRENT_YEAR = '2017' CURRENT_SEMESTER_DISPLAY = 'Fall 2017' SIS_TERM_ID = 2178 TELEBEARS = { 'phase1_start': datetime.datetime(2017, 4, 18), 'phase2_start': datetime.datetime(2017, 7, 18), 'phase1_end': datetime.datetime(2017, 7, 15), 'phase2_end': datetime.datetime(2017, 8, 14), 'adj_start': datetime.datetime(2017, 8, 15), } TELEBEARS_JSON = { 'phase1_start_date': TELEBEARS['phase1_start'].strftime('%m/%d/%Y-%H:%M:%S'), 'phase1_end_date': TELEBEARS['phase1_end'].strftime('%m/%d/%Y-%H:%M:%S'), 'phase1_start_day': 1, 'phase1_end_date': (TELEBEARS['phase1_end'] - TELEBEARS['phase1_start']).days + 1, 'phase2_start_date': TELEBEARS['phase2_start'].strftime('%m/%d/%Y-%H:%M:%S'), 'phase2_end_date': TELEBEARS['phase2_end'].strftime('%m/%d/%Y-%H:%M:%S'), 'phase2_start_day': (TELEBEARS['phase2_start'] - TELEBEARS['phase1_start']).days + 1, 'phase2_end_date': (TELEBEARS['phase2_end'] - TELEBEARS['phase1_start']).days + 1, 'adj_start_date': TELEBEARS['adj_start'].strftime('%m/%d/%Y-%H:%M:%S'), 'adj_start_day': (TELEBEARS['adj_start'] - TELEBEARS['phase1_start']).days + 1, } TELEBEARS_ALREADY_STARTED = datetime.datetime.now() >= TELEBEARS['phase1_start']
true
true
f727a3cd29e902d31223aa1b5f1bbe02c67a9180
4,804
py
Python
features/command_handler.py
DAgostinateur/Woh-Bot-2.0
4e99d97218a59156bacb1669cc1cb6c8807dd5b1
[ "MIT" ]
null
null
null
features/command_handler.py
DAgostinateur/Woh-Bot-2.0
4e99d97218a59156bacb1669cc1cb6c8807dd5b1
[ "MIT" ]
null
null
null
features/command_handler.py
DAgostinateur/Woh-Bot-2.0
4e99d97218a59156bacb1669cc1cb6c8807dd5b1
[ "MIT" ]
null
null
null
import re import discord from commands import set_presence, avatar, erp from commands.admin import list_user_admin, add_user_admin, rm_user_admin from commands.birthday import (set_channel_bd, show_channel_bd, set_user_bd, set_notif_time, list_user_bd, manual_bd_check, show_message_bd, set_message_bd) from commands.cant_be_disabled import disable, enable, help from commands.music import play, leave, repeat, now_playing, resume, pause, volume, next, previous, queue, search class CommandHandler(object): do_not_disable = ["enable", "disable", "help"] dict_cmd_name = "cmd_name" dict_enabled = "enabled" def __init__(self, client): self.parent_client = client self.commands = self.get_commands() self.set_every_command_state() def set_every_command_state(self): if self.parent_client.settings.user_command_states is None: return for cmd in self.commands: if self.command_state_exists(cmd.cmd_name): cmd.enabled = self.get_command_enabled(cmd.cmd_name) def get_command_enabled(self, cmd_name): if self.parent_client.settings.user_command_states is None: return None for cmd_state in self.parent_client.settings.user_command_states: if cmd_state[self.dict_cmd_name] == cmd_name: if cmd_state[self.dict_enabled] == "True": return True else: return False return None def command_state_exists(self, cmd_name): if self.parent_client.settings.user_command_states is None: return False for cmd_state in self.parent_client.settings.user_command_states: if cmd_state[self.dict_cmd_name] == cmd_name: return True return False def get_cmd(self, command_name): """Returns a Command with a command name :param command_name: :return: Command """ for command in self.commands: if command.cmd_name == command_name: return command return None def get_commands(self): return [set_presence.SetPresence(self), disable.Disable(self), enable.Enable(self), manual_bd_check.ManualBDCheck(self), set_notif_time.SetNotifTime(self), add_user_admin.AddUserAdmin(self), rm_user_admin.RmUserAdmin(self), set_message_bd.SetMessageBD(self), show_message_bd.ShowMessageBD(self), set_channel_bd.SetChannelBD(self), show_channel_bd.ShowChannelBD(self), list_user_admin.ListUserAdmin(self), list_user_bd.ListUserBD(self), set_user_bd.SetUserBD(self), avatar.Avatar(self), play.Play(self), leave.Leave(self), resume.Resume(self), pause.Pause(self), now_playing.NowPlaying(self), repeat.Repeat(self), volume.Volume(self), previous.Previous(self), next.Next(self), queue.Queue(self), search.Search(self), erp.Erp(self), help.Help(self)] async def check_message(self, message: discord.Message): for cmd in self.commands: argument = re.compile("^" + self.parent_client.prefix + "[a-z]*").search(message.content.lower()) if argument is not None: if argument.group() == self.parent_client.prefix + cmd.cmd_name: await cmd.command(message) def get_cmd_inlines(self): return [cmd.get_help_inline() for cmd in self.commands] def enable_command(self, command_name): try: cmd = self.get_cmd(command_name) if cmd in self.do_not_disable: return "Attempted to enable an unchangeable command." cmd.enabled = True if self.command_state_exists(cmd.cmd_name): self.parent_client.settings.delete_command_state( {self.dict_cmd_name: cmd.cmd_name, self.dict_enabled: "False"}) return "Enabled '{}'!".format(command_name) except AttributeError: return "Failed to enable command, '{}' doesn't exist.".format(command_name) def disable_command(self, command_name): try: cmd = self.get_cmd(command_name) if cmd in self.do_not_disable: return "Attempted to disable an unchangeable command." cmd.enabled = False if not self.command_state_exists(cmd.cmd_name): self.parent_client.settings.save_user_defaults( command_state={self.dict_cmd_name: cmd.cmd_name, self.dict_enabled: "False"}) return "Disabled '{}'!".format(command_name) except AttributeError: return "Failed to disable command, '{}' doesn't exist.".format(command_name)
42.513274
113
0.648626
import re import discord from commands import set_presence, avatar, erp from commands.admin import list_user_admin, add_user_admin, rm_user_admin from commands.birthday import (set_channel_bd, show_channel_bd, set_user_bd, set_notif_time, list_user_bd, manual_bd_check, show_message_bd, set_message_bd) from commands.cant_be_disabled import disable, enable, help from commands.music import play, leave, repeat, now_playing, resume, pause, volume, next, previous, queue, search class CommandHandler(object): do_not_disable = ["enable", "disable", "help"] dict_cmd_name = "cmd_name" dict_enabled = "enabled" def __init__(self, client): self.parent_client = client self.commands = self.get_commands() self.set_every_command_state() def set_every_command_state(self): if self.parent_client.settings.user_command_states is None: return for cmd in self.commands: if self.command_state_exists(cmd.cmd_name): cmd.enabled = self.get_command_enabled(cmd.cmd_name) def get_command_enabled(self, cmd_name): if self.parent_client.settings.user_command_states is None: return None for cmd_state in self.parent_client.settings.user_command_states: if cmd_state[self.dict_cmd_name] == cmd_name: if cmd_state[self.dict_enabled] == "True": return True else: return False return None def command_state_exists(self, cmd_name): if self.parent_client.settings.user_command_states is None: return False for cmd_state in self.parent_client.settings.user_command_states: if cmd_state[self.dict_cmd_name] == cmd_name: return True return False def get_cmd(self, command_name): for command in self.commands: if command.cmd_name == command_name: return command return None def get_commands(self): return [set_presence.SetPresence(self), disable.Disable(self), enable.Enable(self), manual_bd_check.ManualBDCheck(self), set_notif_time.SetNotifTime(self), add_user_admin.AddUserAdmin(self), rm_user_admin.RmUserAdmin(self), set_message_bd.SetMessageBD(self), show_message_bd.ShowMessageBD(self), set_channel_bd.SetChannelBD(self), show_channel_bd.ShowChannelBD(self), list_user_admin.ListUserAdmin(self), list_user_bd.ListUserBD(self), set_user_bd.SetUserBD(self), avatar.Avatar(self), play.Play(self), leave.Leave(self), resume.Resume(self), pause.Pause(self), now_playing.NowPlaying(self), repeat.Repeat(self), volume.Volume(self), previous.Previous(self), next.Next(self), queue.Queue(self), search.Search(self), erp.Erp(self), help.Help(self)] async def check_message(self, message: discord.Message): for cmd in self.commands: argument = re.compile("^" + self.parent_client.prefix + "[a-z]*").search(message.content.lower()) if argument is not None: if argument.group() == self.parent_client.prefix + cmd.cmd_name: await cmd.command(message) def get_cmd_inlines(self): return [cmd.get_help_inline() for cmd in self.commands] def enable_command(self, command_name): try: cmd = self.get_cmd(command_name) if cmd in self.do_not_disable: return "Attempted to enable an unchangeable command." cmd.enabled = True if self.command_state_exists(cmd.cmd_name): self.parent_client.settings.delete_command_state( {self.dict_cmd_name: cmd.cmd_name, self.dict_enabled: "False"}) return "Enabled '{}'!".format(command_name) except AttributeError: return "Failed to enable command, '{}' doesn't exist.".format(command_name) def disable_command(self, command_name): try: cmd = self.get_cmd(command_name) if cmd in self.do_not_disable: return "Attempted to disable an unchangeable command." cmd.enabled = False if not self.command_state_exists(cmd.cmd_name): self.parent_client.settings.save_user_defaults( command_state={self.dict_cmd_name: cmd.cmd_name, self.dict_enabled: "False"}) return "Disabled '{}'!".format(command_name) except AttributeError: return "Failed to disable command, '{}' doesn't exist.".format(command_name)
true
true
f727a444defc0c229318bcae59c50a66a901568f
737
py
Python
handcoding/fire.py
everyevery/programming_study
ff35e97e13953e4d7a26591f7cdb301d3e8e36c6
[ "MIT" ]
null
null
null
handcoding/fire.py
everyevery/programming_study
ff35e97e13953e4d7a26591f7cdb301d3e8e36c6
[ "MIT" ]
null
null
null
handcoding/fire.py
everyevery/programming_study
ff35e97e13953e4d7a26591f7cdb301d3e8e36c6
[ "MIT" ]
1
2017-04-01T21:34:23.000Z
2017-04-01T21:34:23.000Z
import itertools as it def fire(manager_list, salary_list, productivity_list): acc_list = [val[0] - val[1] for val in it.chain([(0,0)], zip(productivity_list, salary_list))][-1::-1] for i, e in it.takewhile(lambda v: v[0] != 0, zip(range(len(acc_list)-1, -1, -1), acc_list)): acc_list[-1 - manager_list[i]] += e if 0 < e else 0 return acc_list[-1] if __name__ == "__main__": manager_list = [int(val) for val in it.chain([0], input().split())] productivity_list = [int(val) for val in input().split()] salary_list = [int(val) for val in input().split()] print(fire(manager_list, salary_list, productivity_list)) #print(fire([0,0,0,0,1,1,2,2], [1,3,2,2,3,3,0], [2,2,1,1,4,1,4]))
40.944444
97
0.617368
import itertools as it def fire(manager_list, salary_list, productivity_list): acc_list = [val[0] - val[1] for val in it.chain([(0,0)], zip(productivity_list, salary_list))][-1::-1] for i, e in it.takewhile(lambda v: v[0] != 0, zip(range(len(acc_list)-1, -1, -1), acc_list)): acc_list[-1 - manager_list[i]] += e if 0 < e else 0 return acc_list[-1] if __name__ == "__main__": manager_list = [int(val) for val in it.chain([0], input().split())] productivity_list = [int(val) for val in input().split()] salary_list = [int(val) for val in input().split()] print(fire(manager_list, salary_list, productivity_list))
true
true